Struts2文件上传: 一:请选参看Struts2_9中的Struts2上传原理 二:加入Struts2的支持 三:页面 <s:form action="upload" method="post" enctype="multipart/form-data"> <s:textfield name="username" label="用户名"></s:textfield> <s:password name="password" label="密码"></s:password> <s:file name="myfile" label="文件"></s:file> <s:submit></s:submit> </s:form> 四:strus.xml配置说明: <struts> <!-- 设置request的编码方式 --> <constant name="struts.i18n.encoding" value="gbk"></constant> <!-- 上传大文件临时目录 --> <constant name="struts.multipart.saveDir" value="c:\"></constant> <!-- 上传的文件大于多少时将放到临时目录中,否则放到内存中 Struts2默认的大为2097152即2M <constant name="struts.multipart.maxSize" value=""></constant> --> <package name="mengya" extends="struts-default"> <action name="upload" class="com.mengya.action.UploadAction"> <result name="success">/result.jsp</result> </action> </package> </struts> 五:上传的Action说明: /** * Struts2上传 * @author 张明学 * */ public class UploadAction extends ActionSupport { private String username; private String password; /** * 对应页面中的File标签的名称 */ private File myfile; /** * 这个属性由Struts2自动生成。规则:File字段的属性名+FileName和File字段的属性名+ContentType * File字段的属性名+FileName表示上传的文件名 */ private String myfileFileName; /** * File字段的属性名+ContentType表示上传的文件的类型 */ private String myfileContentType; @Override public String execute() throws Exception { InputStream is=new FileInputStream(myfile); /** * 上传到服务器的目录 */ String root=ServletActionContext.getRequest().getRealPath("/upload"); File destFile=new File(root,this.getMyfileFileName()); OutputStream os=new FileOutputStream(destFile); byte[] buffer=new byte[400]; int length=0; while((length=is.read(buffer))>0){ os.write(buffer,0,length); } os.close(); is.close(); return SUCCESS; } public File getMyfile() { return myfile; } public void setMyfile(File myfile) { this.myfile = myfile; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getMyfileContentType() { return myfileContentType; } public void setMyfileContentType(String myfileContentType) { this.myfileContentType = myfileContentType; } public String getMyfileFileName() { return myfileFileName; } public void setMyfileFileName(String myfileFileName) { this.myfileFileName = myfileFileName; } }
相关资源:java中Struts2文件上传问题详解