①.首先导入相应的jar包,然后我们建立一个index.jsp页面。
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>Insert title here</title> </head> <body> <form action="upload.action" method="post" enctype="multipart/form-data"> 标题:<input type="text" name="title"><br> 文件:<input type="file" name="myFile"><br> <input type="submit" value="上传"> </form> </body> </html>②然后我们需要一个Action来处理上传,代码如下:
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import com.opensymphony.xwork2.Action; public class UploadTestAction { private String title; //可以得到上传文件的名称 //规则:输入域的名称+固定字符串FileName private String myFileFileName; //取得文件数据 //规则:File 输入域的名称 private File myFile; // //取得内容类型 // //规则:输入域的名称+固定字符串ContentType private String myFileContentType; public String getMyFileFileName() { return myFileFileName; } public void setMyFileFileName(String myFileFileName) { this.myFileFileName = myFileFileName; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public File getMyFile() { return myFile; } public void setMyFile(File myFile) { this.myFile = myFile; } public String getMyFileContentType() { return myFileContentType; } public void setMyFileContentType(String myFileContentType) { this.myFileContentType = myFileContentType; } public String execute() throws Exception { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream( new FileInputStream(myFile)); os = new BufferedOutputStream( new FileOutputStream("D:\\" + myFileFileName)); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } }finally { if (is != null) {is.close();} if (os != null) {os.close();} } return Action.SUCCESS; } }③Action写完以后再到struts2的配置文件配置一下代码如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 当struts.xml配置文件发生修改,会立刻加载,在生产环境下最好不要配置 --> <constant name="struts.configuration.xml.reload" value="true"/> <!-- 会提供更加友好的提示信息 --> <constant name="struts.devMode" value="true"/> <!-- 需要继承struts-default包,这样就拥有的最基本的功能 --> <package name="upload-package" extends="struts-default"> <action name="upload" class="com.csu.struts2.UploadTestAction"> <result>/success.jsp</result> </action> </package> </struts>
原文地址:http://blog.csdn.net/dq3wrr/article/details/38679661