【发布时间】:2021-03-02 22:32:29
【问题描述】:
我正在尝试将 docx 文件设置为对要作为 附件 下载的 api 的响应。但是当我下载API生成的文件时,它是损坏的并且无法打开,即使初始文件很好并且可以显示。 这是我的控制器方法:
byte[] fileAsBytes= readFileToByteArray(new File(fileLocation))
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader("Content-Disposition", "attachment; filename=" + "output.docx");
response.getOutputStream().write(fileAsBytes);
获取字节数组的方法
public static byte[] readFileToByteArray(File file){
FileInputStream fis = null;
byte[] bArray = new byte[(int) file.length()];
try{
fis = new FileInputStream(file);
fis.read(bArray);
fis.close();
}catch(IOException ioExp){
ioExp.printStackTrace();
}
return bArray;
}
当我尝试打开下载的文件时,它显示“Word 发现无法读取的内容”和“Word 在尝试打开文件时遇到错误”
控制器类中的方法:
@ApiOperation("get file as bytes")
@PostMapping("/get-file")
public void getFileAsbytes(HttpServletRequest request,
HttpServletResponse response) throws IOException {
byte[] fileAsBytes= documentsService.getFileAsBytes();
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader("Content-Disposition", "attachment; filename=" + "output.docx");
response.getOutputStream().write(fileAsBytes);
response.flushBuffer();
}
【问题讨论】:
-
响应对象是HttpServletRespone吗?试试这个:
response.flushBuffer();写入流之后。 -
我测试了您的代码并且工作正常。您如何使用此 API?
-
@JakubBiernaczyk 是的,对象是 HttpServletResponse。我尝试在 response.getOutputStream().write(fileAsBytes) 之后添加 flushBuffer() 但仍然遇到同样的问题。
-
@delephin 我用控制器方法更新了代码,并通过 Swagger 使用它
-
显然问题出在打包文件时大摇大摆。我尝试使用硬编码值从 POST 生成 GET,并在浏览器中调用它,然后下载文件,一切正常。
标签: java http-headers apache-poi httpresponse docx