我想创建一个 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
file.
当我删除时.html
延长并保留test.zip
它可以正确打开。所以我的问题是:
我不知道我还能做什么。我也尝试更换ByteArrayOuputStream
类似的东西:
OutputStream outputStream = response.getOutputStream();
并将方法设置为void所以它什么也没返回,但它创建了.zip
哪个文件被损坏了?
打开包装后在我的 MacBook 上test.zip
我正在得到test.zip.cpgz
这再次给了我test.zip
文件等。
在 Windows 上,正如我所说,.zip 文件已损坏,甚至无法打开它。
我还认为,删除.html
自动扩展将是最好的选择,但如何扩展呢?
希望它没有看起来那么难:)
Thanks