简体   繁体   English

将字节数组转换为文件并下载

[英]Convert Byte Array To File And Download

I am getting byte array from web service.我从 web 服务获取字节数组。 this byte array is the pdf file.这个字节数组是 pdf 文件。 Below code execute well and download file on browser.下面的代码执行良好并在浏览器上下载文件。 But this file is seems corrupt.但这个文件似乎已损坏。 Also additional copy of file gets created on server which I am trying to avoid.此外,我试图避免在服务器上创建额外的文件副本。

byte[] rawFile = myService.getDocument(param1, param2);    
          try (BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(rawFile));
               FileOutputStream fileOutputStream = new FileOutputStream("myfile-1.pdf")) {
            byte dataBuffer[] = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
              fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition","attachment;filename=myfile-1.pdf");
            response.flushBuffer();
          } catch (final Exception ex) {
            ex.printStackTrace();
          }
        }

In a nutshell, below are 2 issue.简而言之,以下是 2 个问题。

  • Downloaded file (on browser) is seems corrupt and not open.下载的文件(在浏览器上)似乎已损坏且未打开。 Generic pdf error message appears.出现通用 pdf 错误消息。
  • File which created on server is opening fine and shows content.在服务器上创建的文件可以正常打开并显示内容。 But this file should not be physically present on server.但是此文件不应实际存在于服务器上。

Downloaded file (on browser) is seems corrupt and not open.下载的文件(在浏览器上)似乎已损坏且未打开。

Because you never sent the file content to the browser.因为您从未将文件内容发送到浏览器。

this file should not be physically present on server.此文件不应实际存在于服务器上。

Then why did you explicitly write it there using FileOutputStream ?那你为什么用FileOutputStream明确地写在那里?


You need to write the file content to the response .您需要将文件内容写入response

byte[] rawFile = myService.getDocument(param1, param2);

response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=myfile-1.pdf");
OutputStream out = response.getOutputStream();
out.write(rawFile);
// no need to close or flush, that happens automatically when you return

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

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