提问者:小点点

如何在AJAX调用后下载文件


如何在AJAX调用后自动下载文件? 现在我的AJAX调用正在将我重定向到资源,但不是下载文件。

这是我的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;
        }
    });

});

这是html标记:

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

共2个答案

匿名用户

因为您正在通过window.location手动重定向它。 有多种方法下载文件,如果你有资源链接。 其中之一是使用download属性。(另外,在将相同的问题作为新问题发布之前,您始终可以尝试搜索是否已经存在相同的问题)。 您可以在这里找到详细的答案:使用JavaScript/jQuery下载文件

匿名用户

您应该做的是确保服务器使用文件url的以下头进行响应

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

然后在ajax中执行以下操作

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