Servlet最古老的上传代码
1 package cn.servlet; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.List; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import org.apache.commons.fileupload.FileItem; 13 import org.apache.commons.fileupload.FileItemFactory; 14 import org.apache.commons.fileupload.FileUploadException; 15 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 16 import org.apache.commons.fileupload.servlet.ServletFileUpload; 17 18 import cn.bean.User; 19 20 public class RegisterServlet extends HttpServlet { 21 22 /** 23 * 24 */ 25 private static final long serialVersionUID = 1L; 26 27 public void doGet(HttpServletRequest request, HttpServletResponse response) 28 throws ServletException, IOException { 29 30 this.doPost(request, response); 31 32 } 33 34 public void doPost(HttpServletRequest request, HttpServletResponse response) 35 throws ServletException, IOException { 36 User user = new User(); 37 request.setCharacterEncoding("utf-8"); 38 boolean isMultipart = ServletFileUpload.isMultipartContent(request); 39 if(isMultipart){ 40 //创建FileItemFactory工厂对象, 41 FileItemFactory factory = new DiskFileItemFactory(); 42 //获得ServletFileUpload对象 43 ServletFileUpload upload = new ServletFileUpload(factory); 44 try { 45 //解析request中的请求,parseRequest方法是ServletFileUpload类的重要方法, 46 //通过对http解析request获取到数据 47 @SuppressWarnings("unchecked") 48 List<FileItem> list = upload.parseRequest(request); 49 boolean flag = false; 50 if(list!=null){ 51 for(FileItem fi:list){ 52 //isFormField方法判断FileItem类对象封装的数据是否为一个普通文本表单字段, 53 //如果是普通表单字段返回一个true,如果是二进制文件表单,返回false 54 if(fi.isFormField()){ 55 if("username".equals(fi.getFieldName())){ 56 user.setUsername(fi.getString("utf-8")); 57 } 58 if("password".equals(fi.getFieldName())){ 59 user.setPassword(fi.getString("utf-8")); 60 } 61 } 62 else 63 { 64 //获得上文件 65 //获取到文件的真实路径 66 user.setPath("/upload/"+fi.getName()); 67 String path = request.getSession().getServletContext().getRealPath("/upload"); 68 System.out.println(path); 69 //创建文件夹 70 File parentPath = new File(path); 71 if(!parentPath.exists()){ 72 parentPath.mkdirs(); 73 } 74 String fiName = fi.getName(); 75 File newFile = new File(path,fiName); 76 try 77 { 78 fi.write(newFile); 79 flag=true; 80 } 81 catch (Exception e) 82 { 83 System.out.println(e.getMessage()); 84 } 85 } 86 } 87 }else{ 88 System.out.println("集合中没有数据"); 89 } 90 if(flag){ 91 System.out.println("如果上传文件成功,数据添加到数据库"); 92 } 93 } catch (FileUploadException e) { 94 // TODO Auto-generated catch block 95 e.printStackTrace(); 96 } 97 response.setCharacterEncoding("utf-8"); 98 } 99 } 100 101 }
View Code
版权声明:本文为smileL原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。