我想读取从文件路径列表中创建一个zip文件。我希望将zip文件作为字节数组,以便我可以将它作为ResponseEntity对象返回到网页。问题是当我试图FileOutputStream它的工作原理。我试过ByteArrayOutputStream压缩文件已损坏。下面是一日2线您在上面看到,如果我使用ByteArrayOutputStream代码创建zip文件到字节数组
//FileOutputStream bos = new FileOutputStream("C:\\files\\zipfile.zip");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
ArrayList<String> filepaths = getAllFiles();
byte[] contents = null;
for(String path : filepaths) {
File pdf = new File(path);
FileInputStream fis = new FileInputStream(pdf);
ZipEntry zipEntry = new ZipEntry(path.substring(path.lastIndexOf(File.separator)+1));
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer,0,len);
}
fis.close();
zos.closeEntry();
zos.flush();
}
contents = new byte[bos.size()];
contents = bos.toByteArray();
zos.close();
bos.close();
,zip文件是似乎已损坏。但如果我使用FileOutputstream我无法打开zip文件及其内容。
这里是我如何发回zip字节数组到网页。所有这些代码发生在弹簧控制器方法内
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/zip"));
headers.setContentDispositionFormData(zipfileNm, zipfileNm);
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;