1. 需要的jar包:
(1)commons-fileupload-1.2.2.jar
(2)commons-io-2.0.1.jar
2.JSP
1、表单必须使用post方式提交
2、表单编码类型
enctype="multipart/form-data"
3、file标签中,name属性必须要写
<s:file label="上传文件:" name="upload"></s:file>
附html代码:
<s:form action="upload.action" theme="simple" namespace="/" method="post" enctype="multipart/form-data">
<s:file label="上传文件:" name="upload"></s:file>
<s:submit value="提交上传"></s:submit>
</s:form>
3.Action
1.三个成员变量的命名是有规范的:
(1)private File upload里的的upoload一样要和你上传提交页面里的name属性值对应一致
(2)文件类型和文件名命名分别为:页面name属性值+ContentType,页面name属性值+FileName
即Action中应该这样定义:
private File upload; //命名应该和上传页面name属性值保持一致
private String uploadContentType; //属性值+ContentType
private String uploadFileName; //属性值+FielName
2.提供setter方法,以便接收对应的数据
3.定义目标文件存放处,用commons-io-2.0.1.jar包提供的FileUtils工具类把上传文件复制到指定位置
附Action的代码:
public class UploadAction extends ActionSupport {
//<s:file label="上传文件:" name="upload"></s:file> //html中file标签的定义
private File upload; //命名应该和上传页面name属性值保持一致
private String uploadContentType; //属性值+ContentType
private String uploadFileName; //属性值+FielName
public void setUpload(File upload) {
this.upload = upload;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String upload() {
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/uploads")
+ "/" + uploadFileName);
try {
//工具类
FileUtils.copyFile(upload, destFile);
} catch (IOException e) {
e.printStackTrace();
}
return SUCCESS;
}
}
单文件下载见http://blog.csdn.net/sunglee_1992/article/details/53033498