Servlet:htm+javascript+css+servlet (ajax)实现上传(能显示进度条)(三)

2014-11-24 09:21:59 · 作者: · 浏览: 3
DiskFileItemFactory factory=new DiskFileItemFactory();
//设置缓冲区大小,超出该文件直接写入到磁盘的大小设置门槛。
factory.setSizeThreshold(10240); //这里默认10KB
//设置用于大于配置的大小阈值设置的临时存储文件目录。
factory.setRepository(uploadTemp);
//创建一个文件上传的句柄
ServletFileUpload upload=new ServletFileUpload(factory);
//设置最大文件尺寸 ,这里是40MB
upload.setSizeMax(41943040);
upload.setHeaderEncoding("utf-8");
// 设置 listener
upload.setProgressListener(listener);
try {
//将解析结果放在LIST中
List list =upload.parseRequest(request);
out.println("遍历所有的 FileItem ...
");
// 遍历 list 中所有的 FileItem
for(FileItem item:list)
{
// 如果是 文本域
if(item.isFormField())
{
if(item.getFieldName().equals("description1")||item.getFieldName().equals("description2"))
{
description = item.getString("UTF-8");
System.out.println("遍历到 "+item.getFieldName()+" ...
"+description+"
");
}
}
else
{
//否则为文件域,当getName为Null说明没有选则文件
if((item.getFieldName().equals("file1")||item.getFieldName().equals("file2"))
&&item.getName()!=null&&!item.getName().equals(""))
{
try
{
// 统一 Linux 与 windows 的路径分隔符
String fileName = item.getName();
//fileName = fileName.substring(fileName.lastIndexOf("\\"));
// 服务器端文件,放在 upload 文件夹下
file=new File(uploadPath,fileName);
if(!file.getParentFile().exists())
file.getParentFile().mkdirs();
if(!file.exists())
file.createNewFile();
item.write(file);
System.out.println("遍历到 "+fileName+" ...
"+description+"
");
} catch (Exception e) {
System.out.println("Request 上传失败!"+e.getMessage());
}
finally //总是立即删除保存表单字段内容的临时文件
{
item.delete();
}
}
}
}
System.out.println("Request 解析完毕,文件上传完毕!");
} catch (Exception e) {
System.out.println("Request 解析异常!"+e.getMessage());
}
out.flush();
out.close();
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
uploadPath=new File(this.getServletContext().getRealPath("upload"));
if(!uploadPath.exists())
uploadPath.mkdirs();
uploadTemp=new File(this.getServletContext().getRealPath("upload/temp"));
if(!uploadTemp.exists())
uploadTemp.mkdirs();
}
}
web.xml
[java]
< xml version="1.0" encoding="UTF-8" >
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/X