Servlet文件上传

1、首先需要导入依赖包

    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

2、获取文件存放目录

// 判断表单是否带有文件
//     if(!ServletFileUpload.isMultipartContent(req))
//              return;

//        1、获取文件存储路径
        String  realPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        System.out.println(realPath);

//    2、正常都是预先创建好的
        File filePath = new File(realPath);
        if(!filePath.exists())
            filePath.mkdirs();

//       3、获取大文件临时存储路径
        String tempPath = this.getServletContext().getRealPath("/WEB-INF/tempPath");
        File tempFile = new File(tempPath);
        if(!tempFile.exists())
            tempFile.mkdirs();

        /**
         * 使用Apache文件上传组件处理文件上传步骤:
         *
         * */
        //4、设置环境:创建一个DiskFileItemFactory工厂,处理文件上传路径或者大小限制
        DiskFileItemFactory  factory = new DiskFileItemFactory();
        factory.setRepository(tempFile);


        //5、核心操作类:创建一个文件上传解析器。
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        //设置上传文件名的中文乱码
        fileUpload.setHeaderEncoding("utf-8");

        //设置单个文件上传大小 2M
//        fileUpload.setFileSizeMax(2*1024*1024);
        fileUpload.setFileSizeMax(2*1024*1024);

        //设置总上传文件大小(有时候一次性上传多个文件,需要有一个上限,此处为10M)
//        fileUpload.setSizeMax(10*1024*1024);
        fileUpload.setSizeMax(10*1024*1024);

        //6、可以监听文件上传进度
        fileUpload.setProgressListener(new ProgressListener() {
            /**
             * @param bytesRead 已经读取的字节数
             * @param contentLength 文件总长度
             * @param items 当前上传的是哪个文件
             */
            @Override
            public void update(long bytesRead, long contentLength, int items) {
                System.out.println("已经读取:"+bytesRead);
                System.out.println("文件总大小:"+contentLength);
                System.out.println("第:"+items+"个文件");            }
        });

        //7、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
        try {
            List<FileItem> fileItems = fileUpload.parseRequest(req);

            for (FileItem item : fileItems)
            {
                if(item.isFormField()){
                    String filedName = item.getFieldName();//普通输入项数据的名
                    //解决普通输入项的数据的中文乱码问题
                    String filedValue = item.getString("UTF-8");//普通输入项的值
                    System.out.println("普通字段:"+filedName+"=="+filedValue);
                   }else{
                    //如果fileitem中封装的是上传文件,得到上传的文件名称,
                    String fileName = item.getName();//文件名
                    //多个文件上传输入框有空 的 异常处理
                    if(fileName==null || "".equals(fileName.trim())){  //去空格是否为空
                        continue;// 为空,跳过当次循环,  第一个没输入则跳过可以继续输入第二个
                     }

                    fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
                   //拼接上传路径。存放路径+上传的文件名
                    String fileRealPath = realPath+"\\"+fileName;
                    //构建输入输出流
                    InputStream in = item.getInputStream(); //获取item中的上传文件的输入流
                    OutputStream out = new FileOutputStream(fileRealPath); //创建一个文件输出流

                    //创建一个缓冲区
                    byte b[] = new byte[1024];
                    //判断输入流中的数据是否已经读完的标识
                    int len = 0;
                    //循环将输入流读入到缓冲区当中,(len=in.read(buffer))!=-1就表示in里面还有数据
                    while((len=in.read(b)) != -1){  //没数据了返回-1
                       //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath+"\\"+filename)当中
                       out.write(b, 0, len);
                    }
                    //关闭流
                    out.close();
                    in.close();
                   //删除临时文件
                     try {
                        Thread.sleep(3000);
                        } catch (InterruptedException e) {
                        e.printStackTrace();
                       }
                       item.delete();//删除处理文件上传时生成的临时文件
                   System.out.println("文件上传成功");
                }


            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        }

 

posted @ 2020-02-23 20:53  门虫不是虫  阅读(229)  评论(0编辑  收藏  举报