I am trying to set a docx file a response to an api to be downloaded as an attachment. But when I download the file generated by the API, it is corrupted and can not be opened, even if the initial file is fine and can be displayed. This is my controller method:
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);
The method used to get the byte array
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;
}
When i try to open the downloaded file it says "Word found unreadable content" and "Word experienced an error when trying to open the file"
The method in the controller 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();
}
The issue is with swagger2 version. This bug is fixed in version 3.0.0