java web文件上传详细解析
目录
- 工具
- 上传案例
- 上传详细解析流程
1.工具
MyEclipse10.7、火狐浏览器、fileupload组件(添加的jar包 commons-fileupload-1.2.2.jar、commons-io-2.2.jar )
2.上传案例《先上案例,如果熟悉的同学可以绕过,直接看后面》
- JSP页面
2.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fieldName = null; String fieldValue = null; //判断form表单传过来的数据MIME是否是<enctype="multipart/form-data"> boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart){ throw new RuntimeException("这个表单提交的数据不是《multipart/form-data》类型!"); } //解析请求的内容 -- fileupload组件 DiskFileItemFactory factory = new DiskFileItemFactory();//产生FileItem的工厂 ServletFileUpload sfu = new ServletFileUpload(factory); List<FileItem> items = new ArrayList<FileItem>(); try { /* * [name=null, StoreLocation=C:\tomcat7\temp1\ upload_5629e1cf_156bc94a7ca__7ffe_00000000.tmp1, * size=5bytes, isFormField=true, FieldName=name, name=test1.zip1, * StoreLocation=C:\tomcat7\temp1\ upload_5629e1cf_156bc94a7ca__7ffe_00000001.tmp1, size=154bytes, * isFormField=false, FieldName=file1] ----->items的值 */ items = sfu.parseRequest(request); for(FileItem item:items){ if(item.isFormField()){ //普通的字段 fieldName = item.getFieldName(); fieldValue = item.getString(); }else{//上传文件的处理 InputStream in = item.getInputStream(); //上传文件的文件名 --test1.zip1 String fileName = item.getName(); if(fileName != null){ fileName = FilenameUtils.getName(fileName); } //存放路径 -- C:\tomcat7\webapps1\FileUpload\files String realPath = getServletContext().getRealPath("/files"); File storeDirectory = new File(realPath); if(storeDirectory.exists()){ //判断文件是否存在 storeDirectory.mkdirs(); //若文件不存在则创建一个 } //将文件写入到上述文件夹中C:\tomcat7\webapps1\FileUpload\files item.write(new File(storeDirectory,fileName)); } } } catch (Exception e) { throw new RuntimeException("解析请求失败!"); } PrintWriter out = response.getWriter(); out.write( fieldName + "=" +fieldValue); }
3.上传详细解析流程跟踪