springboot 和 HttpServletResponse下载多文件方法

@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 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 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 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 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 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 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 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);
}

你可能感兴趣的:(java,前端,servlet)