单个文件上传和批量文件上传,pdf,docx文件的下载

一、单个文件上传

前端代码可参考elementUI,后端代码主要上传一个文件MultipartFile multipartFile

@PostMapping("/upload")
  public ObjectRestResponse uploadKnowledge(@RequestParam(value = "multipartFile") MultipartFile multipartFile) throws IOException {
      Map<String, Object> map = new HashMap<String, Object>();
      System.out.println("multipartFile.getOriginalFilename() = " + multipartFile.getOriginalFilename());
      String originalFilename = multipartFile.getOriginalFilename();
      String substring = originalFilename.substring(originalFilename.lastIndexOf('.'));
      System.out.println(multipartFile.getName());
      if (multipartFile != null) {
          // 设置文件名称
          map.put("nameParam", multipartFile.getName());
          // 设置文件名称
          map.put("fileName", multipartFile.getName());
          // 设置文件类型
          map.put("contentType", multipartFile.getContentType());
          // 设置文件大小
          map.put("fileSize", multipartFile.getSize());

          // 创建文件名称
          String fileName = UUID.randomUUID() + substring;
          // 获取到文件的路径信息
          RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
          ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
          //文件存储路径
          String filePath = "G:\\creo\\product\\" + fileName;

          // 打印保存路径
          System.out.println(filePath);
          // 保存文件的路径信息,因为是本地存的,所以我返回的是可以访问的路径,到时候查可以直接查出来,
          //  将上传文件这个接口抽出来,可以复用,返回的路径可以存到相应的数据库
          map.put("filePath", "192.168.1.125:8765/product/" + fileName);
          // 创建文件
          File saveFile = new File(filePath);
          // 文件保存
          multipartFile.transferTo(saveFile);

      }
      return new ObjectRestResponse().data(map);
  }

postman或者apiFox测试如下:
postman或者apiFox测试

二、批量上传

批量上传主要是传一个路径,然后一层一层的读取文件,将文件上传到服务器中,我的还是上传到本地中。注意上传文件的大小是否有限制,如果报错可以参考:DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144

  • 目标:上传下面这个文件夹
    目标文件夹

  • 后端代码测试:


  @Test
    public void readFiles() throws Exception{
        //上传路径
       String path = "E:\\英语\\【初中英语教资面试】必看资料@Bilibili CocoPolaris";
       readFilesDir(path);
    }

//解析文件夹
private void readFilesDir(String path) throws Exception {
        LinkedList<File> dirList = new LinkedList<>();
        LinkedList<String> fileList = new LinkedList<>();
        File file = new File(path);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isDirectory()){
                dirList.add(file1);
            }else {
                FileInputStream fileInputStream = new FileInputStream(file1);
                MockMultipartFile mockMultipartFile = new MockMultipartFile(file1.getName(), file1.getName(), "application/json", fileInputStream);
                //System.out.println("mockMultipartFile = " + mockMultipartFile.getName());
                fileList.add(file1.getAbsolutePath());
                System.out.println("file1 = " + file1.getAbsolutePath());

                // 创建文件名称
                String fileName = UUID.randomUUID() + "."
                        + file1.getName();

                String filePath = "G:\\temp\\" + fileName;
                // 打印保存路径
                System.out.println(filePath);
                // 创建文件
                File saveFile = new File(filePath);

                // 文件保存
                mockMultipartFile.transferTo(saveFile);

            }
        }

        File temp;
        while ((!dirList.isEmpty())){
            temp=dirList.removeFirst();
            if (temp.isDirectory()){
                files = temp.listFiles();
                if (files==null) continue;
                for (File file1 : files) {
                    if (file1.isDirectory()){
                        dirList.add(file1);
                    }else {
                        FileInputStream fileInputStream = new FileInputStream(file1);
                       MockMultipartFile mockMultipartFile = new MockMultipartFile(file1.getName(), file1.getName(), "application/json", fileInputStream);
                       // System.out.println("mockMultipartFile = " + mockMultipartFile.getName());
                        fileList.add(file1.getAbsolutePath());
                        System.out.println("file1 = " + file1.getAbsolutePath());

                        // 创建文件名称
                        String fileName = UUID.randomUUID() + "."
                                + file1.getName();
                        //存储的路径
                        String filePath = "G:\\temp\\" + fileName;
                        // 打印保存路径
                        System.out.println(filePath);
                        // 创建文件
                        File saveFile = new File(filePath);

                        // 文件保存
                        mockMultipartFile.transferTo(saveFile);
                    }
                }
            }else {
                System.out.println("======================");
            }
        }
    }
  • 结果:
    存储的路径

三、下载文件pdf或docx文件

 public void downLoad(HttpServletResponse response, String path, String fileName) throws FileNotFoundException {
        try {

            path = path.replace(STORE_PATH, LOCAL_STORE_PATH);
            // 取得文件的后缀名。
            File file = new File(path);
            String ext = path.substring(path.lastIndexOf(".") + 1);
            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("utf-8");
            //判断是pdf格式还是docx格式
            if (ext.equals("docx") || ext.equals("doc")) {
                response.setContentType("application/octet-stream");
            } else if (ext.equals("pdf")) {
                response.setContentType("application/pdf");
            }
            String name = URLEncoder.encode(fileName, "UTF-8");
            String fimename = URLDecoder.decode(name, "utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + name + "." + ext);
            response.addHeader("Content-Length", "" + file.length());
            
            OutputStream toClient = response.getOutputStream();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();


            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
posted @ 2022-05-10 11:25  素衣黛眉  阅读(678)  评论(0编辑  收藏  举报