Spring REST - 创建 ZIP 文件并将其发送给客户端

新手上路,请多包涵

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

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

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

        // Creating byteArray stream, make it bufferable and passing this buffer 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 扩展名?
  • 为什么要加?

我不知道我还能做什么。我也在尝试用类似的东西替换 ByteArrayOuputStream

 OutputStream outputStream = response.getOutputStream();

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

在我的 MacBook 上解压 test.zip 我得到 test.zip.cpgz 再次给我 test.zip 文件等等。

在 Windows 上,.zip 文件已损坏,甚至无法打开。

我还想,自动删除 .html 扩展名将是最好的选择,但是如何呢?

希望它没有看起来那么难:)

谢谢

原文由 azalut 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 597
1 个回答

问题已经解决了。

我更换了:

 response.setContentType("application/zip");

和:

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

现在我得到一个清晰、漂亮的 .zip 文件。


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

原文由 azalut 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题