0

My webapp is using Spring MVC. Endpoint below allows user to download a file. When the user saves the file (Chrome, MSIE) in the browser it is broken. It size is 28792 bytes instead of 24567 and content seems to have different encoding. I spent a day trying to fix that but no success. Source file works fine. Please advise. Thanks a lot!

@RequestMapping(method = POST, consumes = MULTIPART_FORM_DATA_VALUE)
public void processFile(MultipartFile file, HttpServletResponse response) {
    try {
        response.setHeader("Content-Encoding","UTF-8");
        Files.copy(Paths.get("c:\\files", "worksheet.xls"), response.getOutputStream());
        response.getOutputStream().flush();
    } catch (Exception ignore) {
    }
}
Vojtech
  • 2,533
  • 9
  • 34
  • 65
  • this solution works for me http://www.java2novice.com/issues/download-file-in-spring-rest-controller/ – deldev Aug 15 '18 at 00:59

3 Answers3

1

If you really want to download a file, I think you should setup your header or response like this:

response.setHeader("Content-Encoding", "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=worksheet.xls");
response.setContentType("application/octet-stream");
Blank
  • 12,308
  • 1
  • 14
  • 32
0

I found out that the problem was in the JavaScript on the page I used to ensure the download starts automatically. For somehow reason it broke file encoding. I finally solved the problem so that instead of writting data to response output stream I stored it in a temporary file and provided a link to it. Then I used jQuery FileDownload plugin to download it. And it works fine.

Community
  • 1
  • 1
Vojtech
  • 2,533
  • 9
  • 34
  • 65
0

As stated in converter, it is possible that your ResponseEntity is "converted". Look up configuration, for example in WebMvcConfigurerAdapter. If any converter is used especially default ones (like json or xml): put a break marker at every converter class write method to find out which converter is used.

Tiina
  • 4,285
  • 7
  • 44
  • 73