struts2实现上传下载(单文件上传与多文件上传的比较)

来源:互联网 发布:activiti引擎源码分析 编辑:程序博客网 时间:2024/05/21 17:54

 struts2没有提供自己的请求解析器,也就是说,struts2不会自己去处理multipart/form-data的请求,它需要调用其他请求解析器,将HTTP请求中的表单域解析出来,但struts2在原有的上传解析器上作了进一步封装,更进一步简化了文件上传,Struts2的struts.properties配置文件中,配置struts2的上传文件解析器struts.multipart.parser=jakarta(srtuts2默认),也可以设置为常用的cos,pell等。

       struts2实现上传下载所必须的2个jar包:commons-fileupload-xxx.jarcommons-io-xxx.jar

一、文件上传

  1.  单文件上传

(1)单文件上传表单视图:

[java] view plaincopy
  1. <body>  
  2.  <form action="/test/upload.action" enctype="multipart/form-data" method="post">  
  3.      <input name="uploadfile" type="file">  
  4.      <input type="submit" value="上传">  
  5.  </form>  
  6. </body>  

注意:表单必须设置enctype="multipart/form-data"method="post"属性,否则上传会出错。

2. 单文件上传Action类

[java] view plaincopy
  1. /** 
  2.  * 文件上传类 
  3.  * @author Ye 
  4.  * 
  5.  */    
  6.  public class UploadAction extends ActionSupport{  
  7.   
  8.         <!--获取上传文件,名称必须和表单file控件名相同-->       
  9.          private File uploadfile;  
  10.   
  11.          <!--获取上传文件名,命名格式:表单file控件名+FileName(固定)-->      
  12.          private String uploadfileFileName;  
  13.   
  14.          //获取上传文件类型,命名格式:表单file控件名+ContentType(固定)   
  15.          private String uploadfileContentType;       
  16.   
  17.          ...//省略属性的getter、setter方法  
  18.         
  19.          //方法一:使用FileUtils的copyFile来实现文件上传  
  20.          public String upload() throws IOException  
  21.          {  
  22.                  //设置上传文件目录    
  23.                  String realpath = ServletActionContext.getServletContext().getRealPath("/image");  
  24.   
  25.                  //判断上传文件是否为空      
  26.                  if(uploadfile!=null)  
  27.                  {  
  28.                          //设置目标文件(根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例)  
  29.                          File savefile = new File(realpath,uploadfileFileName);  
  30.   
  31.                          // 判断上传目录是否存在            
  32.                          if(!savefile.getParentFile().exists())  
  33.                                savefile.getParentFile().mkdirs();  
  34.   
  35.                          //把文件uploadfile 拷贝到 savefile 里,FileUtils类需要commons-io-x.x.x.jar包支持  
  36.                          FileUtils.copyFile(uploadfile,savefile);  
  37.   
  38.                          //设置request对象值       
  39.                          ActionContext.getContext().put("message""上传成功!");  
  40.                  }  
  41.                  return "success";  
  42.           }  
  43.   
  44.           //方法二:使用文件流来实现文件上传  
  45.           public String upload() throws IOException  
  46.           {  
  47.                 FileOutputStream fos = new FileOutputStream("D:\\"+uploadfileFileName);  
  48.           
  49.                 FileInputStream fis = new FileInputStream(uploadfile);  
  50.           
  51.                 byte[] buffer = new byte[1024];  
  52.           
  53.                 int len = 0;  
  54.           
  55.                 while((len=fis.read(buffer))>0)  
  56.                 {  
  57.                    fos.write(buffer,0,len);  
  58.                 }  
  59.                 return "success";  
  60.            }  
  61.   
  62.  }  

注意:记得Action类要继承ActionSupport

3.  配置struts.xml文件

[html] view plaincopy
  1. <package name="hello" namespace="/test" extends="struts-default">  
  2.     <action name="upload" class="action.UploadAction" method="upload">    
  3.      
  4.         <!-- 在struts.xml文件中使用constant元素指定在全局的struts.properties文件中自定义出错信息,value值为*.properties类型的文件名 -->  
  5.         <constant name="struts.custom.i18n.resources" value="struts"></constant>   
  6.   
  7.         <!-- 配置fileUpload的拦截器 -->  
  8.         <interceptor-ref name="fileUpload">  
  9.    
  10.            <!-- 配置允许上传的文件类型 -->  
  11.            <param name="allowedTypes">image/bmp,image/gif,image/jpg</param>      
  12.         
  13.            <!--配置允许上传文件的扩展名,如果有多个用","隔开 -->      
  14.            <param name="allowedExtensions">txt,excel,ppt</param>    
  15.                 
  16.            <!-- 配置允许上传的文件大小,最大为20k -->  
  17.            <param name="maximumSize">20480</param>  
  18.   
  19.         </interceptor-ref>  
  20.   
  21.         <!-- 配置struts2的默认拦截器栈  -->  
  22.         <interceptor-ref name="defaultStack"></interceptor-ref>  
  23.   
  24.        <result>/success.jsp</result>  
  25.   
  26.        <!-- 上传失败时返回的视图页面 -->  
  27.        <result name="input">/index.jsp</result>     
  28.   
  29.      </action>  
  30. </package>  
注意:(1) 拦截器实现要在UploadAction类中继承ActionSupport,否则拦截器无效。

          (2) 必须显示配置引用Struts默认的拦截器栈:defaultStack

          (3) struts的默认上传文件大小为2M,可以用常量来控制扩大上传限制:

                 <constant name="struts.multipart.maxSize" value="104857600"></constant>   //设置上传上限为10M

                  真正的视频网站会使用插件而不是这种web上传的方式上传文件,因为Web上传的稳定性差。

          (4) 在失败的页面视图中使用<s:fielderror/>标签可以输出上传失败的原因,错误信息默认是struts提供的英文字符,如果需要将其转换为中文字符,可在国际化资源文件中配置以下代码:

struts.properties:

[html] view plaincopy
  1. struts.messages.error.content.type.not.allowed = 上传的文件类型不正确           
  2. struts.messages.error.file.too.large= 上传的文件太大  
  3. struts.messages.error.uploading=上传时出现未知错误  

  2.  多文件上传:

   多文件上传原理同单文件上传,主要是在action中定义File[]数组来接收多文件数据。

(1)多文件上传表单视图:

[html] view plaincopy
  1. <body>  
  2.    <s:form action="multiUpload" method="post" namespace="/test3" enctype="multipart/form-data">  
  3.        <s:file name="uploadfile" label="文件1"></s:file>  
  4.        <s:file name="uploadfile" label="文件2"></s:file>  
  5.        <s:file name="uploadfile" label="文件3"></s:file>  
  6.        <s:file name="uploadfile" label="文件4"></s:file>  
  7.        <s:submit value="上传"></s:submit>  
  8.     </s:form>  
  9. </body>   

(2)多文件上传Action类:

[java] view plaincopy
  1. public class UploadAction extends ActionSupport {  
  2.     private File[] uploadfile;  
  3.     private String[] uploadfileFileName;  
  4.     private String[] uploadfileContentType;  
  5.   
  6.         ...//省略属性的getter、setter方法  
  7.   
  8.         //方法一:  
  9.     public String upload() throws IOException {  
  10.         String realpath = ServletActionContext.getServletContext().getRealPath("/image");  
  11.         if (uploadfile != null) {  
  12.             File savepath = new File(realpath);  
  13.             if (!savepath.exists())  
  14.                 savepath.mkdirs();  
  15.             for (int i = 0; i < uploadfile.length; i++) {  
  16.                 File savefile = new File(realpath, uploadfileFileName[i]);  
  17.                 FileUtils.copyFile(uploadfile[i], savefile);  
  18.             }  
  19.             ActionContext.getContext().put("message""上传成功!");  
  20.         }  
  21.         return "success";  
  22.     }  
  23.   
  24.         //方法二:  
  25.         public String upload() throws IOException  
  26.         {  
  27.              for(int i = 0 ; i < uploadfile.length; i ++)  
  28.              {  
  29.                     FileOutputStream fos = new FileOutputStream("D:\\"+uploadfileFileName[i]);  
  30.               
  31.                     FileInputStream fis = new FileInputStream(uploadfile[i]);  
  32.               
  33.                     byte [] buffer = new byte[1024];  
  34.               
  35.                     int len = 0 ;  
  36.               
  37.                     while((len = fis.read(buffer))>0)  
  38.                     {  
  39.                        fos.write(buffer,0,len);  
  40.                     }  
  41.                       
  42.                }  
  43.                return "success";  
  44.          }  
  45.   
  46.  }  

二、文件下载

(1)文件下载Action类

[java] view plaincopy
  1. public class DownloadAction extends ActionSupport {  
  2.       
  3.         //downloaPath属性用于封装被下载文件的路径  
  4.         private String downloadPath;  
  5.   
  6.         //初始化要保存的文件名  
  7.         private String filename;  
  8.   
  9.         //文件保存路径  
  10.         private String savePath;  
  11.   
  12.         public String getSavePath() {  
  13.             return savePath;  
  14.         }  
  15.   
  16.         public void setSavePath(String savePath) {  
  17.             this.savePath = savePath;  
  18.         }    
  19.        
  20.         public String getFilename() {  
  21.                return filename;  
  22.         }  
  23.   
  24.         public void setFilename(String filename) {  
  25.                this.filename = filename;  
  26.         }  
  27.   
  28.         public void setDownloadPath(String downloadPath) {  
  29.         this.downloadPath = downloadPath;  
  30.         }  
  31.   
  32.        // 隐含属性 targetFile ,用于封装下载文件  
  33.     public InputStream getTargetFile() throws FileNotFoundException  
  34.     {  
  35.         return new FileInputStream(downloadPath);  
  36.     }  
  37.       
  38.     public String execute()  
  39.     {  
  40.         return "success";  
  41.     }  
  42.   
  43. }  
(2)配置struts.xml文件:

[html] view plaincopy
  1. <package name="test3_download" extends="struts-default">   
  2.   <action name="download" class="com.action.DownloadAction" method="execute">  
  3.   
  4.      <!-- 对Action类中的文件路径参数设置初始值 -->  
  5.      <param name="downloadPath">${savePath}</param>  
  6.           
  7.         <!-- 设置一个stream类型的result -->  
  8.         <result name="success" type="stream">  
  9.             
  10.            <!-- 设置下载文件的输入流属性名 -->  
  11.            <param name="inputName">targetFile</param>  
  12.   
  13.            <!-- 设置下载文件的文件类型,配置后可以直接在浏览器上浏览,省略则会弹出是保存文件还是打开文件信息的对话框 -->  
  14.           <!-- <param name="contentType">image/jpg</param> -->  
  15.   
  16.            <!-- 设置下载文件的文件名 -->  
  17.            <param name="contentDisposition">attachment;filename=${filename}</param>  
  18.   
  19.            <!-- 设置下载文件的缓冲 -->  
  20.            <param name="bufferSize">2048</param>  
  21.       </result>  
  22.    </action>  
  23.  </package>  
0 0
原创粉丝点击