Loading

文件上传

  1 package com.rzk.servlet;
  2 
  3 
  4 import org.apache.commons.fileupload.FileItem;
  5 import org.apache.commons.fileupload.FileUploadException;
  6 import org.apache.commons.fileupload.ProgressListener;
  7 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  8 import org.apache.commons.fileupload.servlet.ServletFileUpload;
  9 
 10 import javax.servlet.ServletException;
 11 import javax.servlet.http.HttpServlet;
 12 import javax.servlet.http.HttpServletRequest;
 13 import javax.servlet.http.HttpServletResponse;
 14 import java.io.File;
 15 import java.io.FileOutputStream;
 16 import java.io.IOException;
 17 import java.io.InputStream;
 18 import java.util.List;
 19 import java.util.UUID;
 20 
 21 
 22 public class FileServlet extends HttpServlet {
 23     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 24         System.out.println("进来了");
 25         //判断上传的文件是普通表单还是带文件的表单
 26         if (!ServletFileUpload.isMultipartContent(request)) {
 27             return;//终止方法运行,说明这是一个普通表单,直接返回
 28         }
 29 
 30         //创建上传文件的保存路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件
 31         String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
 32         File uploadFile = new File(uploadPath);
 33         if (!uploadFile.exists()) {
 34             uploadFile.mkdir();//创建这个目录
 35         }
 36 
 37         //缓存:临时文件
 38         //临时路径:加入文件超过了预期的大小,我们就把他放到一个临时文件,过几天,或者提醒用户转存为永久
 39         String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
 40         File file = new File(tmpPath);
 41         if (!file.exists()) {//如果临时文件不存在
 42             file.mkdir();//创建这个目录
 43         }
 44 
 45         // 处理上传的文件,一般都需要通过流来获取,我们可以使用request.getInputStream(),原生态的文件上传流获取,十分麻烦
 46         //但是我们都建议使用 Apache的文件上传组件来实现  common-fileupload ,他需要依赖于commons-io 组件
 47 
 48 
 49         /*
 50          *   ServletFileUpload 负责处理上传的文件数据,并将表单中每个输入项封装成一个Fileitem对象
 51          *   在使用servletFileUpload 对象解析请求时需要 DiskFileItemFactory对象
 52          *   所以,我们需要在进行解析工作前构造好 DiskFileItemFactory 对象
 53          *   通过ServletFileUpload对象的构造方法  或 setFileItemFoctory()方法
 54          * 设置ServletFileUpload对象的fileItemFactory属性
 55          *
 56          * */
 57 
 58         try {
 59             //1.创建DiskFileItemFactory对象   处理文件上传路径或者大小限制
 60             DiskFileItemFactory factory = getDiskFileItemFactory(file);
 61             //2.获取ServletFileUpload
 62             ServletFileUpload upload = getServletFileUpload(factory);
 63             //3.处理上传的文件
 64             String msg = uploadParseRequest(upload,request,uploadPath);
 65 
 66             //servlet请求转发消息
 67             request.setAttribute("msg",msg);
 68             request.getRequestDispatcher("info.jsp").forward(request,response);
 69         } catch (FileUploadException ex) {
 70             ex.printStackTrace();
 71         }
 72 
 73 
 74     }
 75 
 76     public static DiskFileItemFactory getDiskFileItemFactory(File file) {
 77         DiskFileItemFactory factory = new DiskFileItemFactory();
 78         //通过这个工厂设置一个缓冲区,当上传的文件大于这个缓冲区的时候,将他放进临时文件
 79         factory.setSizeThreshold(1024 * 1024);//设置缓冲区大小为1M
 80         factory.setRepository(file);//临时目录的保存目录,需要一个File
 81         return factory;
 82     }
 83     public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){
 84         //2.获取ServletFileUpload
 85         ServletFileUpload upload = new ServletFileUpload(factory);
 86         //监听文件上传进度
 87         upload.setProgressListener(new ProgressListener() {
 88             //pBytesRead:已经读取到的文件大小
 89             //pContentLength : 文件大小
 90             public void update(long pBytesRead, long pContentLength, int pItems) {
 91                 System.out.println("总大小" + pContentLength + "已上传" + pBytesRead);
 92             }
 93         });
 94         //处理乱码问题
 95         upload.setHeaderEncoding("UTF-8");
 96         //设置单个文件的最大值
 97         upload.setFileSizeMax(1024 * 1024 * 10);
 98         //设置总共能够上传文件的大小
 99         //1024 = 1kb * 1024 = 1M * 10 = 10M
100         upload.setSizeMax(1024 * 1024 * 10);
101         return upload;
102     }
103 
104     public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath) throws FileUploadException, IOException {
105         //3.处理上传文件
106         System.out.println("进来");
107         String msg = "";
108         //把前端请求解析,封装成FileItem对象,需要从ServletFileUpload对象中获取
109         List<FileItem> fileItems = upload.parseRequest(request);
110         //fileItem 每一个表单对象
111         for (FileItem fileItem : fileItems) {//fileItem
112             //判断上传的文件是普通表单还是带文件的表单
113             if (fileItem.isFormField()) {
114                 //getFieldName指的是前端表单控件的name
115                 String name = fileItem.getFieldName();
116                 String value = fileItem.getString("utf-8");
117                 System.out.println(name + " : " + value);
118             } else {//如果是文件
119                 // ---------------------------处理文件---------------------
120                 String uploadFileName = fileItem.getName();
121                 //可能存在文件名不合法
122                 if (uploadFileName.trim().equals("") || uploadFileName == null) {
123                     //如果名字为空
124                     continue;
125                 }
126                 //获得上传的文件名   /images/popj.png
127                 String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
128                 //获得文件后缀名
129                 String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
130                     /*
131                         如果文件后缀名 fileExtNAME 不是我们锁需要的
132                         就直接return  不处理告诉用户名类型不对
133                      */
134                 //可以使用UUID(唯一识别的通用码  )保证文件名唯一
135                 //UUID.randomUUID() 随机生一个唯一识别的通用码
136 
137                 //网络传输中的东西 都需要序列化
138                 // pojo 实体类   如果想要在多个电脑上运行   传输--》需要把对象都系列化了
139                 //implements Serializable : 标记接口
140 
141 
142                 String uuidPath = UUID.randomUUID().toString();
143                 // ---------------------------存放地址---------------------
144                 //存到哪?  路径uploadPath
145                 //文件真实存在的路径realPath
146                 String realPath = uploadPath + "/" + uuidPath;
147                 //给每个文件创建一个对应的文件夹
148                 File realPathFile = new File(realPath);
149                 if (!realPathFile.exists()) {
150                     realPathFile.mkdir();
151                 }
152 
153                 // ---------------------------文件传输---------------------
154                 //获得文件上传的流
155                 InputStream inputStream = fileItem.getInputStream();
156 
157                 //创建一个文件输出流
158                 //realPath = 真实的文件夹
159                 // 差一个文件 ; 加上输出文件的名字+ "/" + uuidFileName
160                 FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
161 
162                 //创建一个缓冲区
163                 byte[] buffer = new byte[1024 * 1024];
164 
165                 //判断是否读取完毕
166                 int len = 0;
167                 //如果大于0说明还存在数据
168                 while ((len = inputStream.read(buffer)) > 0) {
169                     fos.write(buffer, 0, len);
170                 }
171 
172                 //关闭流
173                 fos.close();
174                 inputStream.close();
175 
176                 msg = "文件上传成功";
177                 fileItem.delete();//上传成功,清除临时文件
178             }
179         }
180         return msg;
181 
182     }
183 
184 }
185  

 

posted @ 2020-04-04 13:22  Rzk  阅读(157)  评论(0编辑  收藏  举报