文件上传

利用Apache的commons-fileupload.jar方便实现文件上传,代码如下:

DiskFileItemFactory factory = new DiskFileItemFactory();  factory.setSizeThreshold(4096);  String path = getServletConfig().getServletContext().getRealPath("/temp");  File file = new File(path);  if(!file.exists())   file.mkdir();  factory.setRepository(file);   String tempName="";  ServletFileUpload upload = new ServletFileUpload(factory);  try {   List fileItems = upload.parseRequest(request);   Iterator i = fileItems.iterator();         while(i.hasNext()) {             FileItem fi = (FileItem)i.next();             String fileName = fi.getName();             if(fileName!=null) {              tempName = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));              fi.write(new File(path + "/" + tempName));             }         }  } catch (Exception e) {   e.printStackTrace();  }    PrintWriter writer = response.getWriter();  writer.print(path + File.separator + tempName);  writer.close();

相关文章
相关标签/搜索