marue
marue

Reputation: 5726

How can i save a file response with jQuery?

I have a django response sending a file to the user, which then is just ignored by the browser. How can i open a filesave dialog to save it instead?

Here is my Django code:

mimetype = "application/x-unknown"
file = somefilefromthedatabase

response = HttpResponse(file, mimetype=mimetype)
response["Content-Disposition"]= "attachment; filename=%s" % os.path.split(file.name)[1]

return response  

When i access the view generating this directly, it saves the file to the database. When accessing it via jquery, nothing happens. jscode is here:

$(".jp-download").click(function(){
    current=$("#download").data('current').find('.id').text();
    $.post('/actions/',{action:'download',item:current});
});

Upvotes: 3

Views: 4113

Answers (2)

SLaks
SLaks

Reputation: 887385

You need to navigate to that URL by setting window.location to trigger a normal download.
You cannot trigger a download via AJAX.

Upvotes: 2

Orbling
Orbling

Reputation: 20602

In order to get it to download, you'll need to pass the right headers, and set the actual page location to the new address, as if you were changing page properly.

I don't think you can initiate a download via an AJAX call. It won't change page anyway if it starts a download.

Either put the parameters as a GET call, or create a form and submit it.

window.location = '/actions/?action=download&item=' + current;

Upvotes: 4

Related Questions