当前位置 主页 > 网站技术 > 代码类 >

    简单操作实现Java jsp servlet文件上传过程解析

    栏目:代码类 时间:2019-10-16 18:03

    实现文件上传的方式

    1、进入http://commons.apache.org/proper/commons-fileupload/using.html

    2、点击用户指南

    3、对着用户指南一步步复制粘贴,并把代码撸成自己想要的样子

    补充:记得要将commons-io-2.4.jar和commons-fileupload-1.2.2.jar这两个包放到编译器里面

    现成的代码

    JSP 前端页面

    <%--
     Created by IntelliJ IDEA.
     User: Administrator
     Date: 2019/10/8
     Time: 16:14
     To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
      <title>作业三第1遍</title>
    </head>
    <body>
    文件上传注意事项:<br>
    <ol>
      <li>提交方式必须是post</li>
      <li>enctype="multipart/form-data"是以字节数据的形式提交表单,否则默认是kv形式,只会提交文件名</li>
      <li>如果以默认的application/x-www-form-urlencode的方式提交,上传的就不是文件本身</li>
    </ol>
    <%--application/x-www-form-urlencoded 以键值对的方式上传 --%>
    <%-- multipart/form-data 以二进制的方式上传 --%>
    <form action="/work/UploadServlet" method="post" enctype="multipart/form-data">
      <input type="text" name="data1" value="data1Value">
      <hr>
      <input type="text" name="data2" value="data2Value">
      <hr>
      <input type="file" name="dataFile">
      <hr>
      <input type="submit" value="上传该表单">
      <hr>
    </form>
    
    
    </body>
    </html>

    Servlet 后台处理页面

    package com.bd25;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletInputStream;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.File;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.Enumeration;
    import java.util.Iterator;
    import java.util.List;
    
    @WebServlet(name = "UploadServlet", urlPatterns = "/UploadServlet")
    public class UploadServlet extends HttpServlet {
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理中文乱码--已经测试这个要不要无所谓
        request.setCharacterEncoding("UTF-8");
    
        //判断是不是传入的一个二进制的流
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //创建一个简单工厂实例
        FileItemFactory factory = new DiskFileItemFactory();
        //创建一个新的文件上传处理程序
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request
        try {
          List<FileItem> fileItems = upload.parseRequest(request);
          //处理上传的项目
          Iterator iter=fileItems.iterator();
          while(iter.hasNext()){
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()){
              //普通域
              processFormField(item);
            }else{
              //文件域 此处注意processUploadFile()方法的参数里面传入request的目的是让下面写文件的时候获取根目录用的
              processUploadFile(item,request);
            }
              
          }
    
        } catch (FileUploadException e) {
          e.printStackTrace();
        }
    
    
        ServletInputStream inputStream = request.getInputStream();
        byte[] bs=new byte[1024];
        int total=-1;
        while ((total=inputStream.read(bs))!=-1){
          System.out.print(new String(bs,0,total));
        }
      }
    
      /**
       * 文件域
       * @param item
       * @param request
       */
      private void processUploadFile(FileItem item, HttpServletRequest request) {
        //获取文件相关信息
        String fileName="";
        if (!item.isFormField()) {
          String fieldName = item.getFieldName();
          fileName = item.getName();
          String contentType = item.getContentType();
          boolean isInMemory = item.isInMemory();
          long sizeInBytes = item.getSize();
          System.out.println("文件名: "+fileName+" 文件属性:"+fieldName+" 文件大小:"+sizeInBytes+" 文件类型:"+contentType);
        }
        //以下是转存操作,找到储存文件的根路径
        String fileRootPath=request.getServletContext().getRealPath("/WEB-INF/upload");
        File dir = new File(fileRootPath);
        if (!dir.exists()){
          dir.mkdirs();
        }
        //写文件
        File file = new File(fileRootPath+"/"+fileName);
        try {
          item.write(file);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    
      /**
       * 普通域
       * @param item
       */
      private void processFormField(FileItem item) {
        String key = item.getFieldName();
        String value = null;
        try {
          //处理中文乱码
          value = item.getString("UTF-8");
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        System.out.println(key+"----"+value);
      }
    
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
      }
    
      @Override
      protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        System.out.println("刷新....");
      }
    
      @Override
      public void init() throws ServletException {
        super.init();
        System.out.println("初始化....");
      }
    }