简体   繁体   English

AJAX 调用后如何下载文件

[英]How to download a file after AJAX call

How can I automatically download a file after an AJAX call?如何在 AJAX 调用后自动下载文件? Now my AJAX call is redirecting me to the resource, but not downloading the file.现在我的 AJAX 调用将我重定向到资源,但不下载文件。

this is my AJAX call:这是我的 AJAX 电话:

$('.download').click(function (e) {
    e.preventDefault();
    let videoId = $('#video').data('video-id');
    $.ajax({
        url: "/video/" + videoId + "/download-link",
        type: "GET",
        success: function (response) {
            window.location = response.link;
        }
    });

});

And this is the html tag:这是 html 标签:

<a href="#" class="download">
     <i class="fas fa-long-arrow-alt-down"></i>Download
</a>

because you are redirecting it manually via window.location .因为您通过window.location手动重定向它。 There are multiple ways to download file if you have resource link.如果您有资源链接,则有多种下载文件的方法。 One of them is to use download attribute.( Also You can always try to search if same question exists already before posting it as new question).其中之一是使用download属性。(您也可以随时尝试搜索是否已经存在相同的问题,然后再将其发布为新问题)。 You can find detailed answer here: Download File Using Javascript/jQuery你可以在这里找到详细的答案: 使用 Javascript/jQuery 下载文件

what you should do is make sure that the server responds with the following header for the file url您应该做的是确保服务器响应文件 url 的以下 header

Content-Disposition: attachment; filename="file-name" // file name is not required, and can be ommitted
// This will make browsers understand that this is a downloadable resource

and then in your ajax do this然后在您的 ajax 中执行此操作

...
window.open(response.link, '_blank');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM