利用 Commons-Fileupload 实现文件上传
MutiFileUpload.java 文件上传封装类
/** *//**
*
*/
package biz;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/** *//**
* commons fileupload 包装类
* @author kiant
* @version Sep 9, 2008
*/
public class MutiFileUpload extends HttpServlet {
private Map<String, String> parameters; //保存普通 form 表单域
private Map<String,FileItem> files; //保存上传文件
private String encoding; //设置编码格式,推荐 jsp 和 处理类 均为 UTF-8
private Long sizeMax; //设置上传数据的最大数据
private int sizeThreshold; //设置内存缓冲区的阀值
private String repositoryPath; //文件超出缓冲区大小时的临时存放目录
private String uploadDir; //上传文件保存文件夹
/**//*
* methods
*/
/** *//**
* 对 request 进行处理
* @throws UnsupportedEncodingException
*/
public void handleRequest(HttpServletRequest request) throws ServletException, UnsupportedEncodingException {
parameters = new HashMap<String, String>();
files = new HashMap<String, FileItem>();
//DiskFileItem工厂,主要用来设定上传文件的参数
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(getSizeThreshold()); //设置内存缓冲区的阀值
if (getRepositoryPath() != null && getRepositoryPath() != "") {
factory.setRepository(new File(getRepositoryPath())); //临时目录,默认
}
// 使用fileItemFactory为参数实例化一个ServletFileUpload对象
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding(getEncoding()); //设置编码格式,推荐 jsp 和 处理类 均为 UTF-8
upload.setSizeMax(getSizeMax()); //设置上传数据的最大数据
// 开始处理表单请求
try {
List items = upload.parseRequest(request);
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (item.isFormField()) { //如果是表单字段
String name = item.getFieldName();
String value = item.getString(getEncoding());
parameters.put(name, value);
} else { //如果是文件字段
String name = item.getFieldName();
files.put(name, item);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
/**//*
* property accessors
*/
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public Map<String, FileItem> getFiles() {
return files;
}
public void setFiles(Map<String, FileItem> files) {
this.files = files;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public Long getSizeMax() {
return sizeMax;
}
public void setSizeMax(Long sizeMax) {
this.sizeMax = sizeMax;
}
public int getSizeThreshold() {
return sizeThreshold;
}
public void setSizeThreshold(int sizeThreshold) {
this.sizeThreshold = sizeThreshold;
}
public String getRepositoryPath() {
return repositoryPath;
}
public void setRepositoryPath(String repositoryPath) {
this.repositoryPath = repositoryPath;
}
public String getUploadDir() {
return uploadDir;
}
public void setUploadDir(String uploadDir) {
this.uploadDir = uploadDir;
}
}
/** *//**
*
*/
package biz;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/** *//**
* commons fileupload 包装类
* @author kiant
* @version Sep 9, 2008
*/
public class MutiFileUpload extends HttpServlet {
private Map<String, String> parameters; //保存普通 form 表单域
private Map<String,FileItem> files; //保存上传文件
private String encoding; //设置编码格式,推荐 jsp 和 处理类 均为 UTF-8
private Long sizeMax; //设置上传数据的最大数据
private int sizeThreshold; //设置内存缓冲区的阀值
private String repositoryPath; //文件超出缓冲区大小时的临时存放目录
private String uploadDir; //上传文件保存文件夹
/**//*
* methods
*/
/** *//**
* 对 request 进行处理
* @throws UnsupportedEncodingException
*/
public void handleRequest(HttpServletRequest request) throws ServletException, UnsupportedEncodingException {
parameters = new HashMap<String, String>();
files = new HashMap<String, FileItem>();
//DiskFileItem工厂,主要用来设定上传文件的参数
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(getSizeThreshold()); //设置内存缓冲区的阀值
if (getRepositoryPath() != null && getRepositoryPath() != "") {
factory.setRepository(new File(getRepositoryPath())); //临时目录,默认
}
// 使用fileItemFactory为参数实例化一个ServletFileUpload对象
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding(getEncoding()); //设置编码格式,推荐 jsp 和 处理类 均为 UTF-8
upload.setSizeMax(getSizeMax()); //设置上传数据的最大数据
// 开始处理表单请求
try {
List items = upload.parseRequest(request);
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (item.isFormField()) { //如果是表单字段
String name = item.getFieldName();
String value = item.getString(getEncoding());
parameters.put(name, value);
} else { //如果是文件字段
String name = item.getFieldName();
files.put(name, item);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
/**//*
* property accessors
*/
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public Map<String, FileItem> getFiles() {
return files;
}
public void setFiles(Map<String, FileItem> files) {
this.files = files;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public Long getSizeMax() {
return sizeMax;
}
public void setSizeMax(Long sizeMax) {
this.sizeMax = sizeMax;
}
public int getSizeThreshold() {
return sizeThreshold;
}
public void setSizeThreshold(int sizeThreshold) {
this.sizeThreshold = sizeThreshold;
}
public String getRepositoryPath() {
return repositoryPath;
}
public void setRepositoryPath(String repositoryPath) {
this.repositoryPath = repositoryPath;
}
public String getUploadDir() {
return uploadDir;
}
public void setUploadDir(String uploadDir) {
this.uploadDir = uploadDir;
}
}
Action 调用包装类进行处理
/** *//**
* Method execute
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws IOException
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
//利用组件读取 "multipart/form-data" 传输流文件的具体参数
getMutiFileUpload().handleRequest(request);
String opusName = getMutiFileUpload().getParameters().get("opusName");
String comments = getMutiFileUpload().getParameters().get("comments");
Integer cid = Integer.parseInt(getMutiFileUpload().getParameters().get("categorie0"));
int fullWidht = Integer.parseInt(getMutiFileUpload().getParameters().get("fullView"));
FileItem fileItem = getMutiFileUpload().getFiles().get("picFile");
EcAccount account = (EcAccount)request.getSession().getAttribute("account");
String fileDir = getMutiFileUpload().getUploadDir() + account.getLoginId(); // 保存目录
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssS");
String fileName = format.format(new Date()); // 保存文件名
fileName = fileDir + "/" + fileName;
String[] strType = fileItem.getContentType().split("/");
String extName = strType[1]; //文件扩展名
//这里我省略了有效性的验证
//填充 opus实体
EcOpus opus = new EcOpus();
opus.setEcAccount(account);
opus.setEcOpusCategorie(getEcOpusBiz().findCategorieID(cid));
opus.setOpusName(opusName);
opus.setOpusComments(comments);
opus.setOriginalView(fileName + "o." + extName);
opus.setLinkView(fileName + "l." + extName);
opus.setSmallView(fileName + "s." + extName);
opus.setFullView(fileName + "f." + extName);
opus.setSubmitted(new Date());
opus.setImageSize(0);
opus.setWidth(0);
opus.setHeight(0);
opus.setComment(0);
opus.setFavourite(0);
opus.setTodayView(0);
opus.setTotalView(0);
opus.setDeleteFlag(Byte.parseByte("0"));
// 获得写入路径
String absoluteDir = servlet.getServletContext().getRealPath("/").replaceAll("\\\\", "/");
// 开始写入
getEcOpusBiz().addOpus(opus, absoluteDir, fileItem, fullWidht, extName);
return mapping.findForward("success");
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("fail");
}
}
/** *//**
* Method execute
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws IOException
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
//利用组件读取 "multipart/form-data" 传输流文件的具体参数
getMutiFileUpload().handleRequest(request);
String opusName = getMutiFileUpload().getParameters().get("opusName");
String comments = getMutiFileUpload().getParameters().get("comments");
Integer cid = Integer.parseInt(getMutiFileUpload().getParameters().get("categorie0"));
int fullWidht = Integer.parseInt(getMutiFileUpload().getParameters().get("fullView"));
FileItem fileItem = getMutiFileUpload().getFiles().get("picFile");
EcAccount account = (EcAccount)request.getSession().getAttribute("account");
String fileDir = getMutiFileUpload().getUploadDir() + account.getLoginId(); // 保存目录
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssS");
String fileName = format.format(new Date()); // 保存文件名
fileName = fileDir + "/" + fileName;
String[] strType = fileItem.getContentType().split("/");
String extName = strType[1]; //文件扩展名
//这里我省略了有效性的验证
//填充 opus实体
EcOpus opus = new EcOpus();
opus.setEcAccount(account);
opus.setEcOpusCategorie(getEcOpusBiz().findCategorieID(cid));
opus.setOpusName(opusName);
opus.setOpusComments(comments);
opus.setOriginalView(fileName + "o." + extName);
opus.setLinkView(fileName + "l." + extName);
opus.setSmallView(fileName + "s." + extName);
opus.setFullView(fileName + "f." + extName);
opus.setSubmitted(new Date());
opus.setImageSize(0);
opus.setWidth(0);
opus.setHeight(0);
opus.setComment(0);
opus.setFavourite(0);
opus.setTodayView(0);
opus.setTotalView(0);
opus.setDeleteFlag(Byte.parseByte("0"));
// 获得写入路径
String absoluteDir = servlet.getServletContext().getRealPath("/").replaceAll("\\\\", "/");
// 开始写入
getEcOpusBiz().addOpus(opus, absoluteDir, fileItem, fullWidht, extName);
return mapping.findForward("success");
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("fail");
}
}
FileItem 文件保存
// 原文件保存
File file = new File(absoluteDir + opus.getOriginalView());
fileItem.write(file);
// 原文件保存
File file = new File(absoluteDir + opus.getOriginalView());
fileItem.write(file);