日期:2014-05-17 浏览次数:20717 次
<form action="/vats/upfileServlet.do" method="post" encType=multipart/form-data > 图片:<input type="file" name="img"/> <input type="submit" value="提交"/> </form>
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); DiskFileUpload du = new DiskFileUpload(); du.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB du.setSizeThreshold(4096);// 设置缓存区大小 ,4 kb; // up 为 /WebRoot 下的 一个目录 du.setRepositoryPath(request.getSession().getServletContext().getRealPath("/up"));// 设置缓存目录 // 得到所有文件 try { List list = du.parseRequest(request); Iterator it = list.iterator(); while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); String fileName = fileItem.getName(); int index = fileName.lastIndexOf('.'); fileName = fileName.substring(index); fileItem.write(new File(request.getSession() .getServletContext().getRealPath("/file")+ "/" + fileName)); System.out.println("上传成功"); } } catch (Exception e) { e.printStackTrace(); } PrintWriter out = response.getWriter(); out.flush(); out.close(); }