servlet代码:(apache组件实现)
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
factory.setRepository(new File(tempPath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(1263509131 * 1024);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
name = item.getName();
name = name.substring(name.lastIndexOf(File.separator) + 1,name.length());
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
item.write(new File("G:/java工具/Tomcat免安装/tomcat/webapps/teleProject",uploadPath + name));// 这里的路径你可以改成你感兴趣的地方
System.out.println(uploadPath + name);
filename = name;
}
}
//可以跳转成功页面
} catch (Exception e) {
// 可以跳转出错页面
e.printStackTrace();
}
}
今天写这个代码很郁闷,一直在List items = upload.parseRequest(request);这里出错;,后来通过大量的查找资料才知道不光要commons-fileupload包,还要commons-io包。