I have a simple Spring Controller setup to return a file (particularly a .CSV) via an AJAX Request. Here's my call which is utilizing YUI's framework which is making a standard XHR:
var downloadFile = Y.all('.downloadLink'); //traverses DOM for all downloadLink <a> tags
downloadFile.on(
'click',
function(e){
var fileName = e.currentTarget.attr('data-id');//retrieves file name
Y.io.request(
'/download/' + fileName,
{
method: 'GET',
on: {
success: function(e) {
alert('success');
},
failure: function(e) {
alert(e.type);
}
}
});
});
And here is my controller:
@RequestMapping( method = RequestMethod.GET, value = "/download/{fileName:.+}")
@ResponseBody
public FileSystemResource download(@PathVariable String fileName) throws IOException {
File file = new File(rootPath + tempDir + '/' + fileName);
try {
if (file.exists()) {
logger.info(fileName + " downloaded");
return new FileSystemResource(file);
} else {
logger.error("Could not download: " + fileName + " does not exist on server");
}
} catch (Exception e) {
logger.error("Error Downloading File");
e.printStackTrace();
}
return null;
}
As suggested in this question, I've tried forcing the download by modifying the method with
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
as well as including an HttpeServletResponse and setting the content type with
response.setContentType("application/force-download");
Without setting the MediaType, my request is successful and the @ResponseBody
returns the contents of my file to the browser. However when I include the MediaType I receive a 406:
406 Not Acceptable: The resource identified by this request is only capable
of generating responses with characteristics not acceptable according to the request "accept" headers.
I've searched the docs but I haven't found which "accepts" parameter I should be using to make this a valid request (if that alone would even resolve this issue). Any thoughts or suggested methods to retrieve my files? Cheers mates and Happy Easter
You need to set
Accept
header when you make a request. Never used YUI but try something like this