How to save file response using jQuery?

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

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 in the database. When accessing it through jquery, nothing happens. jscode is here:

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

To download it, you need to pass the correct headers and set the actual page location to a new address, as if you were changing the page correctly.

I do not think you can initiate a download through an AJAX call. It will not change the page in any way if it starts loading.

GET, .

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

URL-, window.location .
AJAX.

+2

Source: https://habr.com/ru/post/1795099/


All Articles