Reputation: 3123
EDIT
From what I have learned (from comments by nico_ekito) it is not possible to use ajax call to download a file. The solution is to create a hidden <iframe>
that will download the file, described here.
Problem: The browser doesn't show download dialog. Any browser - ff, opera, chrome, safari, ie.
I read the docs about serving files, found this question and, based on this, wrote:
Controller.response().setContentType("text/csv");
Controller.response().setHeader("Content-Disposition", "attachment;filename=public/export/filename.csv");
Controller.response().setHeader("Cache-control", "private");
return ok(CSV.export(data, filename));
Where CSV
is a class:
public class CSV{
public static File export(Map<String, String> data, String filename){
String csv = data.get("data[saveMe]");
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("public/export/" + filename), "UTF-8"));
bw.write(csv);
bw.newLine();
bw.flush();
bw.close();
}catch(UnsupportedEncodingException e){}
catch(FileNotFoundException e){}
catch(IOException e){}
File downloadMe = new File("public/export/" + filename);
return downloadMe;
}
}
On client side, I use dojo
to send POST
request (I also tried with GET
, result is the same):
xhr.post({
url: '/exportData/',
content: {
saveMe: str
}
}).then(function(response){
//do sth
});
Response headers look like that:
Cache-Control private
Content-Disposition attachment;filename=public/export/filename.csv
Content-Type text/csv
Transfer-Encoding chunked
POST
tab in firebug shows proper data in proper csv format. To format data with csv style I use dojox/grid/enhanced/plugins/exporter/CSVWriter
Upvotes: 2
Views: 4301
Reputation: 21564
I think it is not possible to download a file from an Ajax request, see this question: Allow User to Download File using Ajax
You should either use an iframe as suggested in the question, or use a standard HTML form containing your data, and do a post on this form.
Upvotes: 3