实现步骤:
在jsp页面实现在客户端选择上传文件
配置struts.xml , 拦截器会自动接收上传的文件
在Action中写代码把上传的文件存入服务器中
跳转至新页面展示上传的文件
Jsp页面:
……
……
<body>
<form action=”${pageContext.request.contextPath}/upload/uploadAction_saveFile.action”method=”post” enctype=”multipart/form-data”>
上传文件名称:<input type=”file” name=”uploadImage”>
<input type=”submit” value=”上传”>
</form>
</body>
</html>
Action页面 :
package cn.itcast.action;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport{
//这里的变量要和上传表单的name保持一致。
// 这个表示上传文件的存储的临时文件
private File uploadImage;
//上传文件的类型
private String uploadImageContentType;
//上传文件的真实名称
private String uploadImageFileName;
public File getUploadImage() {
return uploadImage;
}
public void setUploadImage(File uploadImage) {
this.uploadImage = uploadImage;
}
public String getUploadImageContentType() {
return uploadImageContentType;
}
public void setUploadImageContentType(String uploadImageContentType) {
this.uploadImageContentType = uploadImageContentType;
}
public String getUploadImageFileName() {
return uploadImageFileName;
}
public void setUploadImageFileName(String uploadImageFileName) {
this.uploadImageFileName = uploadImageFileName;
}
public String saveFile(){
System.out.println("Upload----save()");
//获取要保存的文件路径
String path=ServletActionContext.getServletContext().getRealPath("/fileupload");
//创建一个名为uploadImageFileName的文件
File file=new File(path,uploadImageFileName);
try {
FileUtils.copyFile(uploadImage, file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="upload" namespace="/upload" extends="struts-default">
<action name="uploadAction_saveFile" class="cn.itcast.action.UploadAction" method="saveFile">
<result name="success">/upload/success.jsp</result>
</action>
</package>
</struts>