要进行struts2文件上传,我们需要写一个action类,类中需要定义一个需要上传的文件变量,即 PRivate File upFile;
action类中代码如下:
package struts.action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import javax.servlet.ServletContext;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class FileUploadDemo extends ActionSupport { private File upFile; private String uploadPath; private String upFileContentType;// 文件类型 private String upFileFileName; // 文件名 public File getUpFile() { return upFile; } public void setUpFile(File upFile) { this.upFile = upFile; } public String getUploadPath() { return uploadPath; } public void setUploadPath(String uploadPath) { this.uploadPath = uploadPath; } public String getUpFileContentType() { return upFileContentType; } public void setUpFileContentType(String upFileContentType) { this.upFileContentType = upFileContentType; } public String getUpFileFileName() { return upFileFileName; } public void setUpFileFileName(String upFileFileName) { this.upFileFileName = upFileFileName; } @Override public String execute() throws Exception { ServletContext context = ServletActionContext.getServletContext(); String realPath = context.getRealPath(uploadPath); InputStream is = null; OutputStream os = null; try { is = new FileInputStream(upFile); File file=new File(realPath+"/"+upFileFileName); os = new FileOutputStream(file); int len = 0; byte[] buf = new byte[2048]; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) is.close(); if (os != null) os.close(); } return SUCCESS; }} 其中定义的upFileContentType和upFileFileName字段的前缀upFile必须是定义的文件File的变量名upFile。action类中的uploadPath在struts2.xml文件中可以定义如下:
<action name="FileUploadDemo" class="struts.action.FileUploadDemo" method="execute"> <param name="uploadPath">/upload</param> <result name="success">/demo.jsp</result> </action> 这样,我们就可以在action类中直接使用uploadPath,赋值即为upload。上传页面代码如下:
<form name="uploadForm" id="uploadForm" enctype="multipart/form-data" method="post" action="FileUploadDemo.ac" > <input name="upFile" type="file"/> <input type="submit" value="上传"/></form> 在页面中enctype="multipart/form-data" method="post"为必须项,否则无法进行文件的上传。
当缺少 method="post" 属性时,会报错如下:
Struts Problem ReportStruts has detected an unhandled exception:Messages: No result defined for action struts.action.FileUploadDemo and result inputFile: file:/D:/Eclipse/Workspace/CombOfThreeFrameWorks/WebRoot/WEB-INF/classes/struts.xmlLine number: 22Column number: 21可以定义struts.properties文件
struts.multipart.saveDir=D://Eclipse//Workspace//CombOfThreeFrameWorks 该文件定义为upFile文件上传后的临时存放路径。注:在实际的操作中发现,我们可以不用在action类中定义upFileContentType和upFileFileName字段,可以根据需要自己添加。
新闻热点
疑难解答