图片上传源码(commons-fileupload-1.2.2)分析图片上传源码(commons-fileupload-1.2.2)分析 第一步:生成DiskFileItemFactory 实现接口生成factory DiskFileItemFactory factory = new DiskFileItemFactory(); /** * Constructs an unconfigured instance of this class. The resulting factory * may be configured by calling the appropri...
FileItem
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
* 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.
*
* This method is only guaranteed to work once, 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 File
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
+ "
");
// 在下文中上传文件至数据库时,将对这里改写结束
} 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