2

Follow up question from my last issue which has since been resolved.

I'm trying to download a file via a Spring @Controller by returning a FileSystemResource. I receive a valid HTTP 200 Response and can view all of the file's content in the browser, however I never receive the prompt to download the file. Here's my method:

@RequestMapping(method = RequestMethod.GET, headers="Accept=*/*", value = "/download/{fileName:.+}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public FileSystemResource download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
    File file = new File(path + '/' + fileName);
    response.setContentLength((int)fileName.length());
    response.setContentType("application/force-download");
    response.setHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");//fileName);
    return  new FileSystemResource(file);
}

From the browser:

Response Headers
Content-Disposition | attachment; filename="my_data.CSV"
Content-Length  | 1712
Content-Type    | text/csv

Request Headers
Accept          | */*
Accept-Encoding | gzip, deflate
Accept-Language | en-US,en;q=0.5

Everything appears valid here; any idea why the actual file isn't getting returned? Cheers

Community
  • 1
  • 1
Clay Banks
  • 4,483
  • 15
  • 71
  • 143

2 Answers2

2

For download: i use:

response.setContentType("application/octet-stream");

Note that your result "Content-Type | text/csv" doesn't match what you set

pdem
  • 3,880
  • 1
  • 24
  • 38
  • I've used this but my Content Type remains the same. I'll debug and see when the type gets set because I'm not explicitly defining text/csv anywhere – Clay Banks Apr 10 '15 at 17:56
0

The minimum that worked for me is a combination of the code in the question, plus the octet-stream content type suggestion from @pdem. Everything else seems unnecessary:

@GetMapping(value = "/testcsv")
public @ResponseBody String getFile(HttpServletResponse response){
  String test = "test1, test2, test3";
  response.setContentType("application/octet-stream");
  response.setHeader("Content-Disposition","attachment; filename=\"test.csv\"");
  return test;
}
Kevin Hooke
  • 2,583
  • 2
  • 19
  • 33