标签:
文件上传要求:
首先,写一个upload.jsp:
引入标签库:
<%@ taglib uri="/struts-tags" prefix="s"%>
body体中(struts标签默认表单提交方式为post):
<body> <s:form action="upload" enctype="multipart/form-data"> <s:file name="file"></s:file> <s:submit value="submit"></s:submit> </s:form> </body>
对应的UploadAction为:
package com.test.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport { private File file; // 对应真正上传的文件 private String fileFileName; // 对应上传的文件名 public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } @Override public String execute() throws Exception { InputStream is = new FileInputStream(file); OutputStream os = new FileOutputStream("E:\\Desktop\\" + fileFileName); byte[] buffer = new byte[1024]; int length = 0; while(-1 != (length = is.read(buffer))) { os.write(buffer, 0, length); } os.close(); is.close(); return SUCCESS; } }
结果页面很简单uploadResult.jsp:
<body> Upload success~~ </body>
struts对应的配置为:
<action name="upload" class="com.test.action.UploadAction"> <result name="success">/uploadResult.jsp</result> </action>
web.xml一如既往从struts的部分开始就没变过:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
最后引入struts2中的第三方JAR包,在原有六个包的情况下,添加commons-io-1.3.2.jar,打开http://localhost:8080/struts2/upload.jsp,选择文件即可完成上传。
标签:
原文地址:http://www.cnblogs.com/Code-Rush/p/4669962.html