Java-制作字节数组作为下载
我有一个zip文件作为字节数组byte[],我可以使用Java-制作字节数组作为下载,java,java-6,Java,Java 6,我有一个zip文件作为字节数组byte[],我可以使用 FileOutputStream fos = new FileOutputStream("C:\\test1.zip"); fos.write(decodedBytes); // decodedBytes is the zip file as a byte array fos.close(); 与其将其写入文件并读取作为下载,不如直接将字节数组作为下载, 我试过这
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解决方案也有效。尝试以下方法:
ServletOutputStream outStream = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename="DATA.ZIP"");
outStream.write(decodedBytes);
outStream.flush();
检查此链接:您是否确保decodedBytes中确实包含数据?您是否尝试过不首先压缩数据?@MattBall我在eclipse调试中检查了字节[]的长度,它与物理压缩文件匹配。实际上,字节[]来自DB,它已经压缩并存储在outStream.write之后的BLOB.outStream.flush put中