【发布时间】:2015-10-15 04:02:00
【问题描述】:
我有一个字节数组 (byte[]) 形式的 zip 文件,我可以使用它将其写入文件系统,
FileOutputStream fos = new FileOutputStream("C:\\test1.zip");
fos.write(decodedBytes); // decodedBytes is the zip file as a byte array
fos.close();
我不想将它写入文件并读取它以使其作为下载,而是直接将字节数组作为下载, 我试过了,
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"File.zip\"");
ServletOutputStream outStream = response.getOutputStream();
outStream.write(decodedBytes); // decodedBytes is the zip file as a byte array
这不起作用,我得到的是空文件。如何将字节数组作为下载?
更新: 我添加了 finally 子句并关闭了 ServletOutputStream 并且它起作用了。
}catch (Exception e) {
Log.error(this, e);
} finally {
try{
if (outStream != null) {
outStream.close();
}
} catch (IOException e) {
Log.error(this, "Download: Error during closing resources");
}
}
Pankaj 解决方案也有效。
【问题讨论】:
-
您确定
decodedBytes中确实有数据吗?您是否尝试过不先压缩数据? -
@MattBall 我在 Eclipse 调试中检查了 byte[] 的长度,它与物理 zip 文件匹配。实际上 byte[] 来自 DB,它已经被压缩并存储在一个 BLOB 中。
-
outStream.flush() 放在 outstream.write() 之后