将 docx 文件设置为 HttpServletResponse
Set docx file to HttpServletResponse
我正在尝试将 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 在尝试打开文件时遇到错误”
控制器中的方法class:
@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
中修复
我正在尝试将 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 在尝试打开文件时遇到错误”
控制器中的方法class:
@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
中修复