繁体   English   中英

Generate Zip File - download PDF from Url and Generate Zip to Download in Browser - Broken PDF

[英]Generate Zip File - download PDF from Url and Generate Zip to Download in Browser - Broken PDF

我已经创建了 Rest 服务,我正在尝试生成 Zip 文件。 这个 Zip 文件是从使用方法InputStream inpuStream = new URL(url).openStream()下载的多个 PDF 文件创建的。 我能够生成 Zip 文件,其中包括 PDF 文件,但 PDF 文件已损坏。 即使我尝试从字符串生成它,它也会以损坏的 PDF 出现,并且我收到错误消息“不支持的文件类型或文件已损坏或损坏”。 它的代码很简单,但似乎我无法跟踪错误。 我提供了我的controller,服务方法供大家参考。 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,发现错误..我解决了。 谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM