springboot 和 HttpServletResponse下载多文件方法

该代码片段展示了如何在JavaSpring应用中将多个文件打包成ZIP文件供用户下载。方法包括直接从文件系统读取文件、从输入流或输出流压缩数据,以及使用StreamingResponseBody处理大文件下载。主要涉及HttpServletResponse、ZipOutputStream和文件I/O操作。
摘要由CSDN通过智能技术生成

@GetMapping("/download-multiple-files")
public void downloadMultipleFiles(HttpServletResponse response) throws IOException {
    // Set the content type and header for the response
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=files.zip");

    // Create a ZipOutputStream to write the files to the response output stream
    try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
        // Add file1.txt to the zip file
        zipOut.putNextEntry(new ZipEntry("file1.txt"));
        Files.copy(Paths.get("file1.txt"), zipOut);
        zipOut.closeEntry();

        // Add file2.txt to the zip file
        zipOut.putNextEntry(new ZipEntry("file2.txt"));
        Files.copy(Paths.get("file2.txt"), zipOut);
        zipOut.closeEntry();
    }

    // Flush and close the response output stream
    response.flushBuffer();
}
 

public static void compressStreamsToZip(List<OutputStream> outputStreams, String zipFileName) throws IOException {
    // Create a new ZipOutputStream to write the compressed data to the zip file
    try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName))) {
        // Loop through each output stream and add it to the zip file
        for (int i = 0; i < outputStreams.size(); i++) {
            // Get the current output stream and create a new ZipEntry for it
            OutputStream outputStream = outputStreams.get(i);
            String entryName = "file" + (i + 1) + ".txt";
            zipOut.putNextEntry(new ZipEntry(entryName));

            // Write the contents of the output stream to the zip file
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = outputStream.read(buffer)) > 0) {
                byteOut.write(buffer, 0, length);
            }
            zipOut.write(byteOut.toByteArray());

            // Close the current ZipEntry and output stream
            zipOut.closeEntry();
            outputStream.close();
        }
    }
}


public static void compressFilesToZip(List<InputStream> inputStreams, String zipFileName) throws IOException {
    // Create a new ZipOutputStream to write the compressed data to the zip file
    try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName))) {
        // Loop through each input stream and add it to the zip file
        for (int i = 0; i < inputStreams.size(); i++) {
            // Get the current input stream and create a new ZipEntry for it
            InputStream inputStream = inputStreams.get(i);
            String entryName = "file" + (i + 1) + ".txt";
            zipOut.putNextEntry(new ZipEntry(entryName));

            // Write the contents of the input stream to the zip file
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                zipOut.write(buffer, 0, length);
            }

            // Close the current ZipEntry and input stream
            zipOut.closeEntry();
            inputStream.close();
        }
    }
}


public static void compressStreamsToZip(List<OutputStream> outputStreams, String zipFileName) throws IOException {
    // Create a new ZipOutputStream to write the compressed data to the zip file
    try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName))) {
        // Loop through each output stream and add it to the zip file
        for (int i = 0; i < outputStreams.size(); i++) {
            // Get the current output stream and create a new ZipEntry for it
            OutputStream outputStream = outputStreams.get(i);
            String entryName = "file" + (i + 1) + ".txt";
            zipOut.putNextEntry(new ZipEntry(entryName));

            // Write the contents of the output stream to the zip file
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = outputStream.read(buffer)) > 0) {
                byteOut.write(buffer, 0, length);
            }
            zipOut.write(byteOut.toByteArray());

            // Close the current ZipEntry and output stream
            zipOut.closeEntry();
            outputStream.close();
        }
    }
}


@GetMapping("/download-multiple-files")
public void downloadMultipleFiles(HttpServletResponse response) throws IOException {
    // Set the content type and header for the response
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=files.zip");

    // Create a ZipOutputStream to write the files to the response output stream
    try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
        // Add file1.txt to the zip file
        zipOut.putNextEntry(new ZipEntry("file1.txt"));
        Files.copy(Paths.get("file1.txt"), zipOut);
        zipOut.closeEntry();

        // Add file2.txt to the zip file
        zipOut.putNextEntry(new ZipEntry("file2.txt"));
        Files.copy(Paths.get("file2.txt"), zipOut);
        zipOut.closeEntry();
    }

    // Flush and close the response output stream
    response.flushBuffer();
}


@RequestMapping("/downloadMultipleFiles")
public void downloadMultipleFiles(HttpServletResponse response, @RequestParam("fileNames") List<String> fileNames) throws IOException {
    response.setContentType("application/octet-stream");
    response.setBufferSize(8192);

    for (String fileName : fileNames) {
        File file = new File(fileName);
        InputStream inputStream = new FileInputStream(file);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
        IOUtils.copy(inputStream, response.getOutputStream());
        response.flushBuffer();
        inputStream.close();
    }
}

@GetMapping("/download")
public ResponseEntity<StreamingResponseBody> downloadFiles(HttpServletResponse response) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.set("Content-Disposition", "attachment; filename=\"files.zip\"");

    StreamingResponseBody responseBody = outputStream -> {
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry zipEntry = new ZipEntry("file1.pdf");
        zipOutputStream.putNextEntry(zipEntry);
        Resource resource = new ClassPathResource("file1.pdf");
        File file = resource.getFile();
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fileInputStream.read(bytes)) >= 0) {
            zipOutputStream.write(bytes, 0, length);
        }
        fileInputStream.close();
        zipOutputStream.closeEntry();

        zipEntry = new ZipEntry("file2.pdf");
        zipOutputStream.putNextEntry(zipEntry);
        resource = new ClassPathResource("file2.pdf");
        file = resource.getFile();
        fileInputStream = new FileInputStream(file);
        while ((length = fileInputStream.read(bytes)) >= 0) {
            zipOutputStream.write(bytes, 0, length);
        }
        fileInputStream.close();
        zipOutputStream.closeEntry();

        zipOutputStream.finish();
    };

    return new ResponseEntity<>(responseBody, headers, HttpStatus.OK);
}


@GetMapping("/download-files")
public ResponseEntity<ByteArrayResource> downloadFiles() throws IOException {
    // Read file1.txt and file2.txt into byte arrays
    byte[] file1Content = Files.readAllBytes(Paths.get("file1.txt"));
    byte[] file2Content = Files.readAllBytes(Paths.get("file2.txt"));
    
    // Create a MultiValueMap to hold the response headers
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file1.txt");
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file2.txt");

    // Combine the file contents into a single byte array
    byte[] combinedContents = new byte[file1Content.length + file2Content.length];
    System.arraycopy(file1Content, 0, combinedContents, 0, file1Content.length);
    System.arraycopy(file2Content, 0, combinedContents, file1Content.length, file2Content.length);
    
    // Create a ByteArrayResource with the combined contents
    ByteArrayResource resource = new ByteArrayResource(combinedContents);
    
    // Return a ResponseEntity with the resource, headers, and status code
    return ResponseEntity.ok()
            .headers(headers)
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .contentLength(combinedContents.length)
            .body(resource);
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拼命小孩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值