将docx文件设置为HttpServlet响应



我正在尝试设置一个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();
}

问题在于swagger2版本。此错误已在3.0.0版中修复

最新更新