如何使用jQuery保存文件响应?

时间:2021-11-27 09:55:32

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?

我有一个django响应向用户发送文件,然后浏览器忽略该文件。如何打开文件对话框以保存它?

Here is my Django code:

这是我的Django代码:

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:

当我直接访问生成此视图的视图时,它会将文件保存到数据库中。通过jquery访问它时,没有任何反应。 jscode在这里:

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

2 个解决方案

#1


4  

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.

我不认为您可以通过AJAX调用启动下载。如果开始下载,它不会改变页面。

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

将参数作为GET调用,或创建表单并提交。

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

#2


2  

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

您需要通过设置window.location来导航到该URL,以触发正常下载。您无法通过AJAX触发下载。

#1


4  

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.

我不认为您可以通过AJAX调用启动下载。如果开始下载,它不会改变页面。

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

将参数作为GET调用,或创建表单并提交。

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

#2


2  

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

您需要通过设置window.location来导航到该URL,以触发正常下载。您无法通过AJAX触发下载。