struts2上传

今天在使用struts2上传的过程中无意发现,struts2上传一个文件大小为0字节的文本竟然会报错FileNotFoundException,尝试了好久也没找到答案,最后只能判断文件的大小后上传,至于文件字节为0的怎么处理就看各位了

struts2上传java源码

 1 package com.jzgx.web.action;
 2 
 3 import java.io.File;
 4 
 5 import org.apache.commons.io.FileUtils;
 6 import org.apache.struts2.ServletActionContext;
 7 import org.apache.struts2.convention.annotation.Action;
 8 import org.apache.struts2.convention.annotation.Result;
 9 
10 import com.opensymphony.xwork2.ActionSupport;
11 
12 @Action(value="fileUpload",results={@Result(name="success",location="/result.jsp"),@Result(name="input",location="/error.jsp")})
13 public class FileUploadAction extends ActionSupport{
14     
15     /* 上传文件*/
16     private File doc;
17     /* 上传文件名称  */
18     private String docFileName;
19     /* 获取上传文件类型*/
20     private String docContentType;
21 
22     @Override
23     public String execute() throws Exception {
24         try{
25             //1.获得文件上传的上传目录
26             String realPath=ServletActionContext.getServletContext().getRealPath("/upload");
27             //2.设置保存目标文件的路径和文件名
28             File target=new File(realPath+File.separator+this.getDocFileName());
29             //如果doc.length()=0会出现FileNotFoundException,没想到好的解决方法,暂时先过滤掉
30             if(doc.length()!=0){
31                 //3.copy文件内容,上传文件
32                 FileUtils.copyFile(doc, target);
33             }
34             return "success";
35         }catch(Exception e){
36             e.printStackTrace();
37             return "error";
38         }
39     }
40     
41     public String getDocFileName() {
42         return docFileName;
43     }
44     public void setDocFileName(String docFileName) {
45         this.docFileName = docFileName;
46     }
47 
48     public File getDoc() {
49         return doc;
50     }
51     public void setDoc(File doc) {
52         this.doc = doc;
53     }
54 
55     public String getDocContentType() {
56         return docContentType;
57     }
58     public void setDocContentType(String docContentType) {
59         this.docContentType = docContentType;
60     }
61 }

struts.xml配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 <struts>
 6     <!-- web应用编码字符集 采用GBK-->
 7     <constant name="struts.i18n.encoding" value="GBK"></constant>
 8     <!-- 上传文件的大小限制设成2G -->
 9     <constant name="struts.multipart.maxSize" value="2097152000"></constant>
10 </struts>

 

 

 

posted @ 2013-12-31 23:35  努力挣扎的小兵  阅读(192)  评论(0编辑  收藏  举报