Java - 制作字节数组作为下载
Java - Make byte array as a download
我有一个 zip 文件作为字节数组 (byte[]),我可以使用
将它写入文件系统
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();
我有一个 zip 文件作为字节数组 (byte[]),我可以使用
将它写入文件系统 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();