代码如下
package com.ming;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;import org.apache.commons.fileupload.FileUpload;import org.apache.commons.io.FileUtils;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.apache.struts2.ServletActionContext;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Date;import java.util.Map;public class uploadFile extends ActionSupport { private File myFile; private String myFileContentType; private String myFileFileName; private String destPath; @Override public String execute() { Logger logger = LogManager.getLogger(); // 获取到Action执行的上下文 destPath = ServletActionContext.getServletContext().getRealPath("/"); // 拼接目录 destPath = destPath + "upload/"; // 新建文件 File tmpFile = new File(destPath, new Date().toString() + this.myFileFileName); try{ FileUtils.copyFile(myFile, tmpFile); }catch (Exception e){ logger.info(e); } logger.info(myFileContentType); return SUCCESS; } 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 getMyFileFileName() { return myFileFileName; } public void setMyFileFileName(String myFileFileName) { this.myFileFileName = myFileFileName; }}
核心思路 是 获取到当前action上下文件,接着获取容器上下文,在进行绝对路径拼接,拼接完成以后,新建file文件,然后,文件内容写入即可.
配置文件
image/jpeg,image/gif /success.jsp /error.jsp