from表单上传图片
1.要实现上传图片在form表单必须加上 <form enctype="multipart/form-data">
2.需要导的两个包 commons-fileupload-xx.jar commons-io-xx.jar
包链接:http://pan.baidu.com/s/1jIJ16KY 密码:5clh
以下是servlet中的代码
1 @Override 2 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 3 req.setCharacterEncoding("utf-8"); 4 //判断是否是上传 5 boolean isMultipart = ServletFileUpload.isMultipartContent(req); 6 if(isMultipart) { 7 8 DiskFileItemFactory factory = new DiskFileItemFactory(); 9 //创建request处理器 10 ServletFileUpload upload = new ServletFileUpload(factory); 11 try { 12 List<FileItem> list = upload.parseRequest(req); 13 for (FileItem fileItem : list) { 14 if(fileItem.isFormField()) { 15 //非上传的普通属性 16 System.out.println(fileItem.getString()); 17 }else { 18 //上传处理 19 String filedName = fileItem.getFieldName(); 20 System.out.println(filedName); 21 22 String name = fileItem.getName(); 23 System.out.println(name); 24 //要上传到的路径 25 File file = new File("E://"+name); 26 fileItem.write(file); 27 } 28 } 29 30 31 } catch (Exception e) { 32 e.printStackTrace(); 33 } 34 35 } 36 37 38 }