图片上传源码(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 appropriate se...
图片上传源码(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 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
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 albumList = as.getAlbumList();
req.setAttribute("albumList", albumList);
req.getRequestDispatcher("/albumList.jsp").forward(req,
resp);
} else {
out.print("重复提交");
}
}
}
}
本文档为【图片上传源码(commons-fileupload-1.2.2)分析】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。