Struts2-文件上传下载

来源:互联网 发布:mysql 随机取一条记录 编辑:程序博客网 时间:2024/05/21 17:14

Struts2文件上传
提供 FileUpload 拦截器,用于解析 multipart/form-data 编码格式请求,解析上传文件的内容
fileUpload拦截器 默认在 defaultStack 栈中, 默认会执行的

在Action需要对上传文件内容进行接收

    页面:        <input type="file" name="upload" />    Action :        public class UploadAction extends ActionSupport {            // 接收上传内容            // <input type="file" name="upload" />            private File upload; // 这里变量名 和 页面表单元素 name 属性一致            private String uploadContentType;            private String uploadFileName;        }         * 格式 : 上传表单项name属性 + ContentType 、 上传表单项name属性 + FileName        * 为三个对象 提供 setter 方法

通过FileUtils 提供 copyFile 进行文件复制,将上传文件 保存到服务器端
Struts2文件上传问题解决
配置 input 视图 ,作为上传出错后 跳转页面
在文件上传时,如果发生错误 ,fileUpload拦截器 会设置错误信息,workflow拦截器 跳转到 input 视图

struts.multipart.parser=jakarta 定义文件上传,采用 commons-fileupload 技术
* 同时支持 cos 、pell 上传技术 (如果使用其它上传技术,单独下载jar包 )

通过 struts.multipart.maxSize 常量设置文件上传总大小限制
* struts.multipart.maxSize=2097152 默认上传文件总大小 2MB
* 超过文件总大小,跳转input 视图, 通过 回显错误信息
在struts.xml 设置上传总大小

设置上传文件总大小,对所有上传form有效,只想对当前form进行设置,可以设置fileUpload拦截器属性
FileUpload 拦截器有 3 个属性可以设置.
* maximumSize: 上传文件的最大长度(以字节为单位), 默认值为 2 MB
* allowedTypes: 允许上传文件的类型, 各类型之间以逗号分隔
* allowedExtensions: 允许上传文件扩展名, 各扩展名之间以逗号分隔
如果针对fileUpload 进行参数设置,当出错时,在页面通过 回显错误信息

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}
多文件上传
第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。
第二步:把form表的enctype设置为:“multipart/form-data“,如下:

<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">  <input  type="file" name="uploadImages">  <input  type="file" name="uploadImages"></form>

第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:

public class uploadAction{  private File[] uploadImages;//得到上传的文件  private String[] uploadImagesContentType;//得到文件的类型  private String[] uploadImagesFileName;//得到文件的名称  //这里略省了属性的getter/setter方法  public String saveFiles() throws Exception{        ServletContext sc = ServletActionContext.getServletContext();        String realpath = sc.getRealPath("/uploadfile");        try {            if(uploadImages!=null&&uploadImages.length>0){                 for(int i=0;i<uploadImages.length;i++){                         File destFile = new File(realpath,uploadImageFileNames[i]);                         FileUtils.copyFile(uploadImages[i], destFile);                  }             }         } catch (IOException e) {              e.printStackTrace();}return "success";}}

Struts2文件下载
1) struts2 完成文件下载,通过 结果集类型 (Result Type) stream 来完成的
struts-default.xml 定义
2) 使用Stream结果集 完成文件下载
文件下载原理: 服务器读取下载文件内容,通过Response响应流写回, 设置 ContentType、 ContentDisposition 头信息

public class StreamResult extends StrutsResultSupport {    protected String contentType = "text/plain"; // contentType头信息  (下载文件对应 MIME协议规定类型 )        * html --- text/html . txt--- text/plain     protected String contentDisposition = "inline"; // ContentDisposition头信息 (下载文件打开方式 inline浏览器内部打开, attachment 以附件形式打开)    protected String inputName = "inputStream";  // 需要Action中 提供 getInputStream 方法 返回 InputStream 提供下载文件 内容 }   

Action 提供 InputStream 返回值 getInputStream 方法 ——- 指定下载文件流
配置 stream 结果集 参数 contentTypeActiongetContentTypeServletActionContext.getServletContext().getMimeType(filename);streamattachment;filename={filename} —- 在Action 提供 getFilename
* 下载附件名乱码问题 , IE和火狐 解决不同

public String encodeDownloadFilename(String filename, String agent)            throws IOException {        if (agent.contains("Firefox")) { // 火狐浏览器            filename = "=?UTF-8?B?"                    + new BASE64Encoder().encode(filename.getBytes("utf-8"))                    + "?=";        } else { // IE及其他浏览器            filename = URLEncoder.encode(filename, "utf-8");        }        return filename;    }
0 0
原创粉丝点击