Struts 1 对Apache的commons-fileupload进行了再封装,把上传文件封装成FormFile对象

定义UploadForm:

[java]  view plain copy print ? Struts 1 之文件上传_html Struts 1 之文件上传_封装_02
  1. private FormFilefile;       //上传的文件  
  2. private Stringtext;    //文件备注  
  3. //省略setter、getter  
 

JSP:

[html]  view plain copy print ? Struts 1 之文件上传_html Struts 1 之文件上传_封装_02
  1. <html:from action="/upload?method=upload" enctype="multipart/form-data">  
  2.    
  3. 文件:<html:file property="file"></html:file>  
  4. <br/>  
  5. 备注:<html:textarea property="text"></html:textarea>  
  6. <br/>  
  7. <html:submit value=”开始上传”/>  
  8.    
  9. </html:form>  

 

处理上传操作的action:

 

[java]  view plain copy print ? Struts 1 之文件上传_html Struts 1 之文件上传_封装_02
  1. UploadForm uploadForm = (UploadForm) form;  
  2.    
  3. StringBuffer buffer = new StringBuffer();  
  4.    
  5. if(uploadForm.getFile()!= null && uploadForm.getFile().getSize()>0){  
  6.       //获取文件夹/WEB-INF/classes  
  7.       File classes = new File(getClass().getClassLoader().getResource("").getFile());  
  8.        
  9.       //获取文件夹/upload  
  10.       File uploadFolder = new File(classes.getParentFile().getParentFile(),"upload");  
  11.       uploadFolder.mkdirs();  
  12.    
  13.       //保存到/upload文件夹下面  
  14.       File file = new File(uploadFolder, uploadForm.getFile().getFilename());  
  15.        
  16.       OutputStreat ous = null;  
  17.       InputStream ins = null;  
  18.       try{  
  19.              byte [] byt = new byte [1024];  
  20.              int len = 0;  
  21.              ins =uploadForm.getFile().getInputStream();  
  22.              ous = new FileOutputStream(file);  
  23.              while((len = ins.read(byt))!=-1){  
  24.                     ous.write(byt,0,len);  
  25.              }  
  26.       }finally{  
  27.              ins.close();  
  28.              ous.close();  
  29.       }  
  30.       //点击即可下载  
  31.       buffer.append("文件:"+"<a href=upload/>"+file.getName()+"target=_blank>"+file.getName()+"</a><br/>");  
  32. }else{  
  33.       buffer.append("没有选择文件!<br/>");  
  34. }  
  35. buffer.append("备注:"+ uploadForm.getText()+"<br/>");  
  36. response.setCharacterEncoding("UTF-8");  
  37. response.getWriter().writer(buffer.toString());