apache fileupload上传组件

DiskFileItemFactory factory = new DiskFileItemFactory();
//超过2M以上的文件 通过临时文件夹来上传
factory.setSizeThreshold(2048*1024);
myProgressListener getBarListener = new myProgressListener(req);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(getBarListener);
//字符编码,当读取上传表单的各部分时会用到该encoding
upload.setHeaderEncoding("gbk");  

System.out.println("将进度监听器加载进去");
try {
List formList = upload.parseRequest(req);
Iterator formItem = formList.iterator();
// 将进度监听器加载进去
String path="";
while (formItem.hasNext()) {
FileItem item = (FileItem) formItem.next();
if (item.isFormField()) {

System.out.println("Field Name:" + item.getFieldName());
path=item.getString();
System.out.println(path);


} else {
String fileName = item.getName().substring(item.getName().lastIndexOf("\\")+1);
File file = new File(path
+ "\\" + fileName);
System.out.println(file.getPath());
OutputStream out = item.getOutputStream();
InputStream in = item.getInputStream();
req.getSession().setAttribute("outPutStream", out);
req.getSession().setAttribute("inPutStream", in);
item.write(file);
item.delete();
}

}
} catch (FileUploadException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

你可能感兴趣的:(apache)