我想创建一个 ZIP 文件,其中包含我从后端收到的存档文件,然后将此文件发送给用户。这2天我一直在寻找答案,但找不到合适的解决方案,也许你可以帮助我:)
目前,代码是这样的(我知道我不应该全部在Spring Controller 中,但不要在意,它只是为了测试目的,找到使它起作用的方法):
@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
扩展? - 为什么要添加?
我不知道我还能做什么。我还尝试将 ByteArrayOutputStream
替换为:
OutputStream outputStream = response.getOutputStream();
并将方法设置为 void 所以它什么都不返回,但是它创建了损坏的 .zip
文件?
在我的 MacBook 上解压 test.zip
后,我得到 test.zip.cpgz
再次给了我 test.zip
文件等等。
如我所说,在 Windows 上,.zip 文件已损坏,甚至无法打开。
我也认为,自动删除 .html
扩展名将是最好的选择,但是如何呢?
希望它没有看起来那么难:)
谢谢
最佳答案
问题解决了。
我换了:
response.setContentType("application/zip");
与:
@RequestMapping(value = "/zip", produces="application/zip")
现在我得到了一个清晰、漂亮的 .zip
文件。
如果你们中的任何人有更好或更快的提议,或者只是想提供一些建议,那么请继续,我很好奇。
关于java - Spring REST - 创建 ZIP 文件并将其发送到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27952949/