Struts2文件上传
Struts2提供 FileUpload拦截器,用于解析 multipart/form-data 编码格式请求,解析上传文件的内容,fileUpload拦截器 默认在defaultStack栈中, 默认会执行的
页面:<input type="file" name="upload" />
在Action需要对上传文件内容进行接收 :
private File upload; // <input type="file" name="upload" />这里变量名 和 页面表单元素 name 属性一致 private String uploadContentType;//格式 :上传表单项name属性 + ContentType 、 上传表单项name属性 + FileName private String uploadFileName; public void setUpload(File upload) {//为三个对象 提供 setter 方法 this.upload = upload; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; }
通过FileUtils 提供 copyFile 进行文件复制,将上传文件保存到服务器端
FileUtils.copyFile(upload, new File("d:/upload",uploadFileName));
关于struts2中文件上传细节:
1.关于控制文件上传大小
在default.properties文件中定义了文件上传大小:struts.multipart.maxSize=2097152 上传文件默认的总大小 2m
2.在struts2中默认使用的是commons-fileupload进行文件上传。
# struts.multipart.parser=cos
# struts.multipart.parser=pell
struts.multipart.parser=jakarta (如果使用pell,cos进行文件上传,必须导入其jar包)
3.如果出现问题,需要配置input视图,在页面上可以通过<s:actionerror>展示错误信息.在页面上展示的信息,全是英文,要想展示中文,国际化
struts-messages.properties 文件里预定义 上传错误信息,通过覆盖对应key 显示中文信息
struts.messages.error.uploading=Error uploading: {0}
struts.messages.error.file.too.large=The file is to large to be uploaded: {0} "{1}" "{2}" {3}
struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}
修改为
struts.messages.error.uploading=上传错误: {0}
struts.messages.error.file.too.large=上传文件太大: {0} "{1}" "{2}" {3}
struts.messages.error.content.type.not.allowed=上传文件的类型不允许: {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=上传文件的后缀名不允许: {0} "{1}" "{2}" {3}
{0}:<input type=“file” name=“uploadImage”>中name属性的值
{1}:上传文件的真实名称
{2}:上传文件保存到临时目录的名称
{3}:上传文件的类型(对struts.messages.error.file.too.large是上传文件的大小)
4.关于多文件上传时的每个上传文件大小控制以及上传文件类型控制.
1.多文件上传
只需要将action属性声明成List集合或数组就可以。
private List<File> upload; private List<String> uploadContentType; private List<String> uploadFileName;
2.怎样控制每一个上传文件的大小以及上传文件的类型
在fileupload拦截器中,通过其属性进行控制.
maximumSize---每一个上传文件大小
allowedTypes--允许上传文件的mimeType类型.
allowedExtensions--允许上传文件的后缀名.
<interceptor-ref name="defaultStack"> <param name="fileUpload.allowedExtensions">txt,mp3,doc</param> </interceptor-ref>
多文件上传案例:
import java.io.File; import java.util.List; import org.apache.commons.io.FileUtils; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport { // 在action类中需要声明三个属性 private List<File> upload; private List<String> uploadContentType; private List<String> uploadFileName; public List<File> getUpload() { return upload; } public void setUpload(List<File> upload) { this.upload = upload; } public List<String> getUploadContentType() { return uploadContentType; } public void setUploadContentType(List<String> uploadContentType) { this.uploadContentType = uploadContentType; } public List<String> getUploadFileName() { return uploadFileName; } public void setUploadFileName(List<String> uploadFileName) { this.uploadFileName = uploadFileName; } @Override public String execute() throws Exception { for (int i = 0; i < upload.size(); i++) { System.out.println("上传文件的类型:" + uploadContentType.get(i)); System.out.println("上传文件的名称:" + uploadFileName.get(i)); // 完成文件上传. FileUtils.copyFile(upload.get(i), new File("d:/upload", uploadFileName.get(i))); } return null; } }
<s:actionerror/> <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data"> <input type="file" name="upload"><br> <input type="file" name="upload"><br> <input type="file" name="upload"><br> <input type="submit" value="上传"> </form>
<struts> <constant name="struts.custom.i18n.resources" value="message"></constant> <constant name="struts.multipart.maxSize" value="20971520"></constant> <package name="default" namespace="/" extends="struts-default"> <action name="upload" class="cn.itcast.action.UploadAction"> <result name="input">/upload.jsp</result> <interceptor-ref name="defaultStack"> <param name="maximumSize">2097152</param> <param name="fileUpload.allowedExtensions">txt,mp3,doc</param> </interceptor-ref> </action> </package> </struts>
struts2中文件下载
通过<result type="stream">完成
<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
在StreamResult类中有三个属性:
protected String contentType = "text/plain"; //用于设置下载文件的mimeType类型
protected String contentDisposition = "inline";//用于设置进行下载操作以及下载文件的名称
protected InputStream inputStream; //用于读取要下载的文件。
要在action类中定义三个方法用于在XML文件中通过ognl获取值
// 设置下载文件mimeType类型 public String getContentType() { String mimeType = ServletActionContext.getServletContext().getMimeType(filename); return mimeType; } // 获取下载文件名称 public String getDownloadFileName() throws UnsupportedEncodingException { return DownloadUtils.getDownloadFileName(ServletActionContext.getRequest().getHeader("user-agent"), filename); } public InputStream getInputStream() throws FileNotFoundException,UnsupportedEncodingException { filename = new String(filename.getBytes("iso8859-1"), "utf-8"); // 解决get请求中文名称乱码. FileInputStream fis = new FileInputStream("d:/upload/" + filename); return fis; }
要在配置文件中配置
<result type="stream"> <param name="contentType">${contentType}</param> <!-- 调用当前action中的getContentType()方法 --> <param name="contentDisposition">attachment;filename=${downloadFileName}</param> <param name="inputStream">${inputStream}</param><!-- 调用当前action中的getInputStream()方法 --> </result>
注:
1:在struts2中进行下载时,如果使用<result type="stream">它有缺陷,例如:下载点击后,取消下载,服务器端会产生异常。
在开发中的解决方案:可以下载一个struts2下载操作的插件,它解决了stream问题。
2:处理浏览器之间不同的编码的getDownloadFileName方法
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import sun.misc.BASE64Encoder; public class DownloadUtils { public static String getDownloadFileName(String agent, String filename) throws UnsupportedEncodingException { if (agent.contains("MSIE")) { // IE浏览器 filename = URLEncoder.encode(filename, "utf-8"); } else if (agent.contains("Firefox")) { // 火狐浏览器 BASE64Encoder base64Encoder = new BASE64Encoder(); filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?="; } else { // 其它浏览器 filename = URLEncoder.encode(filename, "utf-8"); } return filename; } }
下载案例:
<body> <a href="${pageContext.request.contextPath}/download?filename=a.txt">a.txt</a><br> <a href="${pageContext.request.contextPath}/download?filename=捕获.png">捕获.png</a><br> </body>
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import org.apache.struts2.ServletActionContext; import cn.itcast.utils.DownloadUtils; import com.opensymphony.xwork2.ActionSupport; public class DownloadAction extends ActionSupport { private String filename; // 要下载文件的名称 public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } // 设置下载文件mimeType类型 public String getContentType() { String mimeType = ServletActionContext.getServletContext().getMimeType( filename); return mimeType; } // 获取下载文件名称 public String getDownloadFileName() throws UnsupportedEncodingException { return DownloadUtils.getDownloadFileName(ServletActionContext .getRequest().getHeader("user-agent"), filename); } public InputStream getInputStream() throws FileNotFoundException, UnsupportedEncodingException { filename = new String(filename.getBytes("iso8859-1"), "utf-8"); // 解决中文名称乱码. FileInputStream fis = new FileInputStream("d:/upload/" + filename); return fis; } @Override public String execute() throws Exception { System.out.println("进行下载...."); return SUCCESS; } }
<action name="download" class="cn.itcast.action.DownloadAction"> <result type="stream"> <param name="contentType">${contentType}</param> <!-- 调用当前action中的getContentType()方法 --> <param name="contentDisposition">attachment;filename=${downloadFileName}</param> <param name="inputStream">${inputStream}</param><!-- 调用当前action中的getInputStream()方法 --> </result> </action>
来源:https://www.cnblogs.com/fengmingyue/p/6149201.html