我需要编写一个代码来将字节数组转换为ZIP文件,并将其下载到Spring中。
字节数组来自最初是ZIP文件的webservice。ZIP文件有一个文件夹,该文件夹包含2个文件。我编写了下面的代码来将字节数组转换为ZipInputStream。但我无法转换成ZIP文件。请帮我这个忙。
这是我的密码。
ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(bytes));
ZipEntry entry = null;
while ((entry = zipStream.getNextEntry()) != null) {
String entryName = entry.getName();
FileOutputStream out = new FileOutputStream(entryName);
byte[] byteBuff = new byte[4096];
int bytesRead = 0;
while ((bytesRead = zipStream.read(byteBuff)) != -1)
{
out.write(byteBuff, 0, bytesRead);
}
out.close();
zipStream.closeEntry();
}
zipStream.close(); 发布于 2015-10-14 15:28:21
我在这里假设您想要将字节数组写入ZIP文件。由于发送的数据也是一个ZIP文件,而要保存的数据也是ZIP文件,所以应该不会有问题。
需要两个步骤:将其保存在磁盘上并返回文件。
1)磁盘部分保存:
File file = new File(/path/to/directory/save.zip);
if (file.exists() && file.isDirectory()) {
try {
OutputStream outputStream = new FileOutputStream(new File(/path/to/directory/save.zip));
outputStream.write(bytes);
outputStream.close();
} catch (IOException ignored) {
}
} else {
// create directory and call same code
}
}2)现在要把它拿回来并下载,您需要一个控制器:
@RequestMapping(value = "/download/attachment/", method = RequestMethod.GET)
public void getAttachmentFromDatabase(HttpServletResponse response) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFileName() + "\"");
response.setContentLength(file.length);
FileCopyUtils.copy(file as byte-array, response.getOutputStream());
response.flushBuffer();
}我已经编辑了我的代码,所以您必须在它100%适合您之前进行一些更改。如果这是你要找的东西请告诉我。否则,我会删除我的答覆。好好享受吧。
https://stackoverflow.com/questions/33129023
复制相似问题