1. action中加上file属性
2. form表单中加上 input type="file"
3. form表单属性加上enctype="multipart/form-data"
4. action类中加上xxxFileName, xxxContentType属性,以便获取文件名和类型
5. 配置<constant name="struts.multipart.saveDir" value="D:/TDDOWNLOAD" />属性
package com.wolfgang.action; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport; @Controller("uploadFile") public class FileUploadAction extends ActionSupport{ private File uploadfile; private String uploadfileFileName; private String uploadfileContentType; public File getUploadfile() { return uploadfile; } public String getUploadfileFileName() { return uploadfileFileName; } public void setUploadfileFileName(String uploadfileFileName) { this.uploadfileFileName = uploadfileFileName; } public String getUploadfileContentType() { return uploadfileContentType; } public void setUploadfileContentType(String uploadfileContentType) { this.uploadfileContentType = uploadfileContentType; } public void setUploadfile(File uploadfile) { this.uploadfile = uploadfile; } public String upload() { try { FileUtils.copyFile(uploadfile, new File("D:/baiduyundownload/myeclipse.10/MyEclipse 10/"+uploadfileFileName)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return SUCCESS; } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'upload.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="uploadFile" enctype="multipart/form-data" method="post"> 选择文件:<input type="file" name="uploadfile"/></br> <input type="submit" value="提交"/> </form> </body> </html>
ServletActionContext.getServletContext().getRealPath("/upload_files/")+"/"+uploadfileFileName
可以获取当前部署服务的绝对地址