gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:44:23 24 4
gpt4 key购买 nike

我正在从网络服务获取字节数组。这个字节数组就是pdf文件。下面的代码执行良好并在浏览器上下载文件。但这个文件似乎已损坏。另外,我试图避免在服务器上创建额外的文件副本。

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();
}
}

简而言之,以下是 2 个问题。

  • 下载的文件(在浏览器上)似乎已损坏并且无法打开。出现通用 pdf 错误消息。
  • 在服务器上创建的文件可以正常打开并显示内容。但该文件不应该实际存在于服务器上。

最佳答案

Downloaded file (on browser) is seems corrupt and not open.

因为您从未将文件内容发送到浏览器。

this file should not be physically present on server.

那你为什么要使用FileOutputStream显式地把它写在那里?

<小时/>

您需要将文件内容写入响应

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

关于java - 将字节数组转换为文件并下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58698709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com