图片上传源码(commons-fileupload-1.2.2)分析
题记:文章是供自己查看方便,所以没有进行格式化,请见谅!
第一步:生成DiskFileItemFactory
DiskFileItemFactory factory = new DiskFileItemFactory();
/**
* Constructs an unconfigured instance of this class. The resulting factory
* may be configured by calling the appropriate setter methods.
*/
public DiskFileItemFactory() {
this(DEFAULT_SIZE_THRESHOLD, null);
}
/**
* Constructs a preconfigured instance of this class.
*
* @param sizeThreshold The threshold, in bytes, below which items will be
* retained in memory and above which they will be
* stored as a file.
* @param repository The data repository, which is the directory in
* which files will be created, should the item size
* exceed the threshold.
*/
public DiskFileItemFactory(int sizeThreshold, File repository) {
this.sizeThreshold = sizeThreshold;
this.repository = repository;
}
向diskFileItemFctory指定参数
// 设置最多只允许在内存中存储的数据,单位:字节
factory.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()(默认10kb)的值时数据存放在硬盘的目录
factory.setRepository(new File("d:\\temp"));
/**
* Sets the directory used to temporarily store files that are larger
* than the configured size threshold.
*
* @param repository The directory in which temporary files will be located.
*
* @see #getRepository()
*
*/
public void setRepository(File repository) {
this.repository = repository;
}
第二步:生成ServletFileUpload
根据第一步得到的factory生成servletFileUpload对象
/**
* Constructs an instance of this class which uses the supplied factory to
* create <code>FileItem</code> instances.
*
* @see FileUpload#FileUpload()
* @param fileItemFactory The factory to use for creating file items.
*/
public ServletFileUpload(FileItemFactory fileItemFactory) {
super(fileItemFactory);
}
向servletFileUpload对象指定参数
// 设置允许用户上传文件大小,单位:字节,这里设为1m 值为-1没有大小限制
sevletFileUpload.setSizeMax(1 * 1024 * 1024);
/**
* Sets the maximum allowed size of a complete request, as opposed
* to {@link #setFileSizeMax(long)}.
*
* @param sizeMax The maximum allowed size, in bytes. The default value of
* -1 indicates, that there is no limit.
*
* @see #getSizeMax()
*
*/
public void setSizeMax(long sizeMax) {
this.sizeMax = sizeMax;
}
第三步:通过servletFileUpload读取request上传信息
List fileItems = sevletFileUpload.parseRequest(req);
/**
* Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
* compliant <code>multipart/form-data</code> stream.
*
* @param request The servlet request to be parsed.
*
* @return A list of <code>FileItem</code> instances parsed from the
* request, in the order that they were transmitted.
*
* @throws FileUploadException if there are problems reading/parsing
* the request or storing files.
*/
public List /* FileItem */ parseRequest(HttpServletRequest request)
throws FileUploadException {
return parseRequest(new ServletRequestContext(request));
}
第四步:将读取的信息写入到指定目录
item.write(new File( D:/WorkSpace/BlogV1.4/WebContent/uploadImages/"+ m.group(1)));
/**
* A convenience method to write an uploaded item to disk. The client code
* is not concerned with whether or not the item is stored in memory, or on
* disk in a temporary location. They just want to write the uploaded item
* to a file.
* <p>
* This implementation first attempts to rename the uploaded item to the
* specified destination file, if the item was originally written to disk.
* Otherwise, the data will be copied to the specified file.
* <p>
* This method is only guaranteed to work <em>once</em>, the first time it
* is invoked for a particular item. This is because, in the event that the
* method renames a temporary file, that file will no longer be available
* to copy or rename again at a later time.
*
* @param file The <code>File</code> into which the uploaded item should
* be stored.
*
* @throws Exception if an error occurs.
*/
public void write(File file) throws Exception {
if (isInMemory()) {
FileOutputStream fout = null;
try {
fout = new FileOutputStream(file);
fout.write(get());
} finally {
if (fout != null) {
fout.close();
}
}
} else {
File outputFile = getStoreLocation();
if (outputFile != null) {
// Save the length of the file
size = outputFile.length();
/*
* The uploaded file is being stored on disk
* in a temporary location so move it to the
* desired file.
*/
if (!outputFile.renameTo(file)) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(
new FileInputStream(outputFile));
out = new BufferedOutputStream(
new FileOutputStream(file));
IOUtils.copy(in, out);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
}
} else {
/*
* For whatever reason we cannot write the
* file to disk.
*/
throw new FileUploadException(
"Cannot write uploaded file to disk!");
}
}
}
附后台实现部分代码:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html; charset=GB2312");
PrintWriter out = resp.getWriter();
HttpSession session = req.getSession();
session.setMaxInactiveInterval(20);
String submit = (String) session.getAttribute("submit");
String flag = req.getParameter("flag");
if (flag != null && flag.equals("ajax")) {
if (submit != null) {
out.print("重复提交");
}
} else {
AlbumService as = new AlbumService();
// submit=null代表第一次提交,不为null代表重复提交
if (submit == null) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置最多只允许在内存中存储的数据,单位:字节
factory.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
factory.setRepository(new File("d:\\temp"));
ServletFileUpload sevletFileUpload = new ServletFileUpload(
factory);
// 设置允许用户上传文件大小,单位:字节,这里设为2m 值为-1没有大小限制
sevletFileUpload.setSizeMax(1 * 1024 * 1024);
// 开始读取上传信息
List fileItems = sevletFileUpload.parseRequest(req);
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();
// 正则匹配,过滤路径取文件名
String regExp = ".+\\\\(.+)$";
// 过滤掉的文件类型
String[] errorType = { ".exe", ".com", ".cgi", ".asp" };
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result) {
for (int temp = 0; temp < errorType.length; temp++) {
if (m.group(1).endsWith(errorType[temp])) {
throw new IOException(name
+ ": 非法文件类型禁止上传");
}
}
try {
// 保存上传的文件到指定的目录
// 在下文中上传文件至数据库时,将对这里改写开始
item.write(new File(
"D:/WorkSpace/BlogV1.4/WebContent/uploadImages/"
+ m.group(1)));
as.uploadAlbum(m.group(1),
req.getContextPath()
+ "/uploadImages/");
out.print(name + " " + size
+ "<br>");
// 在下文中上传文件至数据库时,将对这里改写结束
} catch (Exception e) {
out.println(e);
}
} else {
throw new IOException("fail to upload");
}
}
}
} catch (IOException e) {
out.println(e);
} catch (FileUploadException e) {
out.println(e);
}
// 最后把session中的值置为false,表示对表单提交做过操作
session.setAttribute("submit", "submit");
List<AlbumBean> albumList = as.getAlbumList();
req.setAttribute("albumList", albumList);
req.getRequestDispatcher("/albumList.jsp").forward(req, resp);
} else {
out.print("重复提交");
}
}
}
}