将多个文件从angular typescript发送到spring并作为zip文件夹返回以便下载?

j91ykkif  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(289)

我想在一个数组中发送多个文件到spring,并创建一个zip文件夹进行下载

w8ntj3qf

w8ntj3qf1#

上传控制器:

@Autowired
  StorageService storageService;

  @PostMapping("/upload")
  public ResponseEntity<ResponseMessage> uploadFiles(@RequestParam("files") MultipartFile[] files) {
    String message = "";
    try {
      storageService.zip(files);

      message = "Uploaded the files successfully";
      return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
    } catch (Exception e) {
      message = "Fail to upload files!";
      return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
    }
  }

存储服务

public void zip(MultipartFile[] files) {
    List<Path> filepaths = new ArrayList();
    for (MultipartFile file : files) {
        Path filepath = Paths.get("my/tmp/dir", file.getOriginalFilename());

        filepaths.add(filepath);

        try (OutputStream os = Files.newOutputStream(filepath)) {
            os.write(file.getBytes());
        }
    }

    File zip = new File("path/to/my/zip");
    try { zip.createNewFile(); }

    FileOutputStream output = null;
    try { output = new FileOutputStream(zip); }
    ZipOutputStream out = new ZipOutputStream(output);

    try {
        for (Path filepath : filepaths) {
            File f = new File(filepath);
            FileInputStream input = new FileInputStream(f);
            ZipEntry e = new ZipEntry(f.getName());
            out.putNextEntry(e);

            byte[] bytes = new byte[1024];
            int length;
            while((length = input.read(bytes)) >= 0) {
                out.write(bytes, 0, length);
            }
            input.close();
        }          

        out.close();
        output.close();
    }
}

相关问题