今天看了一下Struts2中文件上传的部分,现总结一下。
1.上传界面
<s:form action="upload" namespace="/document" method="post" enctype="multipart/form-data">
<s:file name="doc" label="请选择文档"></s:file>
<s:submit value="上传"></s:submit>
</s:form>
2.Action
package org.ygy.action;
import java.io.File;
import org.apache.struts2.ServletActionContext;
import org.ygy.util.FileUtil;
import com.opensymphony.xwork2.ActionSupport;
public class DocumentAction extends ActionSupport {
private static final long serialVersionUID = -7219843607831256046L;
private File doc;//上传的文件
private String docFileName;//上传的文件名
public File getDoc() {
return doc;
}
public void setDoc(File doc) {
this.doc = doc;
}
public String getDocFileName() {
return docFileName;
}
public void setDocFileName(String docFileName) {
this.docFileName = docFileName;
}
public String upload() {
String root = ServletActionContext.getServletContext().getRealPath("/upload");
System.out.println(this.getDocFileName() + "," + root);
FileUtil.write(doc, root + File.separator + this.getDocFileName());
return SUCCESS;
}
}
配置文件
<package name="document" namespace="/document" extends="struts-default">
<action name="upload" class="org.ygy.action.DocumentAction" method="upload">
<result name="success">/upload_success.jsp</result>
</action>
</package>
要注意的是Action的编写,开始以为是这样:
假设HTML的file标签name属性的value是doc,那么,Action中的变量名应该是这样
即变量名前缀都和file标签一致才可以。private File doc;//上传的文件 private String docFileName;//上传的文件名 private String docContentType;
之后看到官方文档上的例子:
<s:form action="doUpload" method="post" enctype="multipart/form-data">
<s:file name="upload" label="File"/>
<s:submit/>
</s:form>
package com.example;
import java.io.File;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private File file;
private String contentType;
private String filename;
public void setUpload(File file) {
this.file = file;
}
public void setUploadContentType(String contentType) {
this.contentType = contentType;
}
public void setUploadFileName(String filename) {
this.filename = filename;
}
public String execute() {
//...
return SUCCESS;
}
}
才明白,这里应该是用set方法注入进来的,所以变量名是什么都可以,只要有和file标签一致的set方法就可以了。一定要多看官方文档啊。