日期:2014-05-17 浏览次数:20711 次
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
uploadFile(request,response);
}
private void uploadFile(HttpServletRequest request, HttpServletResponse response){
String dir = "d:/upload";
File file = new File(dir);
if(!file.exists())
file.mkdirs();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//防止中文文件名乱码
upload.setHeaderEncoding("UTF-8");
try {
List<FileItem> items = upload.parseRequest(request);
if (items != null) {
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
continue;
} else {
//File fullFile=new File(item.getName());
File savedFile=new File(dir+File.separator+item.getName());
item.write(savedFile);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
//结束upload. 如果没有这一行, 浏览器里面一直是uploading....
try {
response.getOutputStream().println("200 OK");
} catch (IOException e) {
e.printStackTrace();
}
}