48

我想创建 .zip 文件,其中包含我从后端收到的压缩文件,然后将此文件发送给用户。2天来我一直在寻找答案,但找不到合适的解决方案,也许你可以帮助我:)

现在,代码是这样的:(我知道我不应该在 spring 控制器中做所有事情,但不要关心,它只是为了测试目的,找到让它工作的方法)

    @RequestMapping(value = "/zip")
    public byte[] zipFiles(HttpServletResponse response) throws IOException{
        //setting headers
        response.setContentType("application/zip");
        response.setStatus(HttpServletResponse.SC_OK);
        response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");

        //creating byteArray stream, make it bufforable and passing this buffor to ZipOutputStream
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
        ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);

        //simple file list, just for tests
        ArrayList<File> files = new ArrayList<>(2);
        files.add(new File("README.md"));

        //packing files
        for (File file : files) {
            //new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
            zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
            FileInputStream fileInputStream = new FileInputStream(file);

            IOUtils.copy(fileInputStream, zipOutputStream);

            fileInputStream.close();
            zipOutputStream.closeEntry();
        }

        if (zipOutputStream != null) {
            zipOutputStream.finish();
            zipOutputStream.flush();
            IOUtils.closeQuietly(zipOutputStream);
        }
        IOUtils.closeQuietly(bufferedOutputStream);
        IOUtils.closeQuietly(byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

但问题是,使用代码,当我输入 URL:localhost:8080/zip 我得到文件:test.zip.html 而不是 .zip 文件

当我删除 .html 扩展名并仅保留 test.zip 时,它会正确打开如何避免返回此 .html 扩展名?为什么要添加?

我不知道我还能做什么。我还尝试将 ByteArrayOutputStream 替换为:

OutputStream outputStream = response.getOutputStream();

并将该方法设置为无效,因此它不返回任何内容,但它创建了..zip 文件,它是..损坏的?

在我的 macbook 上解压test.zip后,我得到了test.zip.cpgz,它再次给了我 test.zip 文件等等。

正如我所说,在 Windows 上,.zip 文件已损坏,甚至无法打开。

我还认为,自动删除 .html 扩展名将是最好的选择,但是如何呢?希望它不像看起来那么难:)谢谢

4

4 回答 4

38

似乎解决了。我更换了:

response.setContentType("application/zip");

和:

@RequestMapping(value = "/zip", produces="application/zip")

现在我得到了清晰、漂亮的 .zip 文件 :)

如果你们中的任何人有更好或更快的提议,或者只是想提供一些建议,那么请继续,我很好奇。

于 2015-01-14T22:36:19.377 回答
36
@RequestMapping(value="/zip", produces="application/zip")
public void zipFiles(HttpServletResponse response) throws IOException {

    //setting headers  
    response.setStatus(HttpServletResponse.SC_OK);
    response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");

    ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());

    // create a list to add files to be zipped
    ArrayList<File> files = new ArrayList<>(2);
    files.add(new File("README.md"));

    // package files
    for (File file : files) {
        //new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
        zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
        FileInputStream fileInputStream = new FileInputStream(file);

        IOUtils.copy(fileInputStream, zipOutputStream);

        fileInputStream.close();
        zipOutputStream.closeEntry();
    }    

    zipOutputStream.close();
}
于 2016-11-09T00:12:05.997 回答
17
@RequestMapping(value="/zip", produces="application/zip")
public ResponseEntity<StreamingResponseBody> zipFiles() {
    return ResponseEntity
            .ok()
            .header("Content-Disposition", "attachment; filename=\"test.zip\"")
            .body(out -> {
                var zipOutputStream = new ZipOutputStream(out);

                // create a list to add files to be zipped
                ArrayList<File> files = new ArrayList<>(2);
                files.add(new File("README.md"));

                // package files
                for (File file : files) {
                    //new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
                    zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                    FileInputStream fileInputStream = new FileInputStream(file);

                    IOUtils.copy(fileInputStream, zipOutputStream);

                    fileInputStream.close();
                    zipOutputStream.closeEntry();
                }

                zipOutputStream.close();
            });
}
于 2019-11-15T21:24:56.303 回答
4

我正在使用REST Web ServiceofSpring Boot并且我已经将端点设计为始终返回ResponseEntity,无论是JSONorPDF还是ZIP,我想出了以下解决方案,该解决方案部分受到denov's answer这个问题以及另一个问题的启发,在该问题中我学会了如何转换ZipOutputStreambyte[]ResponseEntity作为端点的输出。

无论如何,我创建了一个简单的实用程序类,其中包含两种方法pdfzip文件下载

@Component
public class FileUtil {
    public BinaryOutputWrapper prepDownloadAsPDF(String filename) throws IOException {
        Path fileLocation = Paths.get(filename);
        byte[] data = Files.readAllBytes(fileLocation);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/pdf"));
        String outputFilename = "output.pdf";
        headers.setContentDispositionFormData(outputFilename, outputFilename);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

        return new BinaryOutputWrapper(data, headers); 
    }

    public BinaryOutputWrapper prepDownloadAsZIP(List<String> filenames) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/zip"));
        String outputFilename = "output.zip";
        headers.setContentDispositionFormData(outputFilename, outputFilename);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteOutputStream);

        for(String filename: filenames) {
            File file = new File(filename); 
            zipOutputStream.putNextEntry(new ZipEntry(filename));           
            FileInputStream fileInputStream = new FileInputStream(file);
            IOUtils.copy(fileInputStream, zipOutputStream);
            fileInputStream.close();
            zipOutputStream.closeEntry();
        }           
        zipOutputStream.close();
        return new BinaryOutputWrapper(byteOutputStream.toByteArray(), headers); 
    }
}

现在端点可以使用专门为or定制的数据和自定义标头轻松返回ResponseEntity<?>,如下所示。byte[]pdfzip

@GetMapping("/somepath/pdf")
public ResponseEntity<?> generatePDF() {
    BinaryOutputWrapper output = new BinaryOutputWrapper(); 
    try {
        String inputFile = "sample.pdf"; 
        output = fileUtil.prepDownloadAsPDF(inputFile);
        //or invoke prepDownloadAsZIP(...) with a list of filenames
    } catch (IOException e) {
        e.printStackTrace();
        //Do something when exception is thrown
    } 
    return new ResponseEntity<>(output.getData(), output.getHeaders(), HttpStatus.OK); 
}

BinaryOutputWrapper是一个简单的不可变POJO类,我使用private byte[] data;org.springframework.http.HttpHeaders headers;作为字段创建,以便从实用方法 返回data和返回。headers

于 2018-06-05T03:35:57.113 回答