实现文件上传的方式有很多种,如smartupload,输入输出流以及其他方式。struts2也提供了文件上传给开发人员,相比之下struts2的文件上传更加简单快速。在开发中文件上传是比不可少的,因此这也是一个比较重要的知识点。下面就来写一下struts2的文件上传。
1.写一个表单用来选择文件
这里不能忘记写enctype="multipart/form-data",这一点在开发中可能会被遗漏
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>struts2文件上传</title>
</head>
<body>
<form action="uploadAction.action" enctype="multipart/form-data" method="post">
选择文件:<input type="file"/ name="picture"> <!-- 这里的picture和后面的action里的必须一致 -->
<input type="submit" value="上传"/>
</form>
</body>
</html>
文件上传使用的提交方式必须使用post提交,原因相信大家都知道。
2.写一个处理文件上传的action
这里需要注意,名称要和表单里的name保持一致,这是struts2的一些规定
package org.lxh.action;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
public class UploadAction {
private File picture;
private String pictureFileName; //FileName是固定写法,前面的picture就是表单里的name属性
private String pictureContentType;
public File getPicture() {
return picture;
}
public void setPicture(File picture) {
this.picture = picture;
}
public String getPictureFileName() {
return pictureFileName;
}
public void setPictureFileName(String pictureFileName) {
this.pictureFileName = pictureFileName;
}
public String getPictureContentType() {
return pictureContentType;
}
public void setPictureContentType(String pictureContentType) {
this.pictureContentType = pictureContentType;
}
public String upload() throws Exception {
String flag="failure";
//取得真实目录
String path=ServletActionContext.getServletContext().getRealPath("/image");
File file=new File(path,pictureFileName);
//如果目录不存在就创建一个
if(!file.getParentFile().exists())
file.getParentFile().mkdirs();
//使用FileUtil工具类保存文件,这里不能少了commons-io包
if(picture!=null){
FileUtils.copyFile(picture, file);
ServletActionContext.getContext().put("tip", "成功");
flag="success";
}else{
ServletActionContext.getContext().put("tip", "失败");
}
return flag;
}
}
这里需要使用一个工具类,需要commons-io包的支持,另外要对文件目录做判断,如果不存在就创建目录。之后保存一个提示信息,在结果页面显示。