问题描述
我已经创建了 Rest Service 并且我正在尝试生成 Zip 文件。此 Zip 文件由使用方法 InputStream inpuStream = new URL(url).openStream()
下载的多个 PDF 文件创建。我能够生成包含 PDF 文件但 PDF 文件已损坏的 Zip 文件。
即使我尝试从字符串生成它,它也会以损坏的 PDF 格式生成,并且我收到错误消息“不支持的文件类型或文件已损坏或损坏”。它的代码很简单,但似乎我无法跟踪错误。
我已经提供了我的控制器,服务方法供您参考。
1)控制器:
@GetMapping("/getZipFile")
public void getZipFile(HttpServletResponse response) throws RestException {
try {
ByteArrayOutputStream baos = generateZipService.getZipFile();
ServletoutputStream responSEOutPutStream = response.getoutputStream();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setStatus(HttpServletResponse.SC_OK);
response.addheader("Content-disposition","attachment; filename=\"GeneratedZipFile.zip\"");
responSEOutPutStream.write(baos.toByteArray());
responSEOutPutStream.flush();
} catch (Exception e) {
throw new RestException("Error In downloading Zip File");
}
}
2)服务方式
public ByteArrayOutputStream getZipFile() throws Exception{
List<ZipFileName> zipFileNames= zipFileNameDao.getZipFileName();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOut= new ZipOutputStream(baos);
for (String fileName : zipFileNames) {
InputStream inpuStream = new ByteArrayInputStream( "this is test to generarte pdf test file this is test tdfsfs this is test to generarte pdf test file this is test tdfsfs".getBytes(Charsets.UTF_8) );
createZipFile(inpuStream,zipOut,fileName);
inpuStream.close();
}
zipOut.flush();
baos.flush();
zipOut.close();
baos.close();
return baos;
}
3)createzipfile from service method :
```private void createZipFile(InputStream inputStream,ZipOutputStream zipOut,String fileName) throws IOException {
ZipEntry zipEntry = new ZipEntry(fileName+".pdf");
BufferedInputStream bis = new BufferedInputStream(inputStream);
zipOut.putNextEntry(zipEntry);
zipOut.write(IoUtils.toByteArray(inputStream));
zipOut.closeEntry();
bis.close();
inputStream.close();
}
另外,另一个问题是关于使用渠道。当您有大文件要从服务器下载时,我阅读的频道会更好。我的文件不到 20 kb,所以我应该使用 Java.nio 还是只使用 Zipoutputstream 就可以了。
我尝试使用“response.setContentType("APPLICATION/ZIP")”,但它并没有改变项目的结果。 谢谢你的帮助..
解决方法
代码运行良好,唯一缺少的是使用 openStream() 方法通过身份验证,因此我得到了损坏的 PDF。我用记事本++打开pdf,发现错误.. 我解决了。 谢谢