我想讀取從文件路徑列表中創建一個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;