从jquery下载具有现有路径的文件的最简单方法

The simplest way to download file with existing path from jquery?

本文关键字:文件 最简单 方法 路径 jquery 下载      更新时间:2024-02-19

我浏览了十几页,提出了"如何从jQuery下载文件"的问题,但仍然没有找到简单的解决方案。

我的jQuery内置ajax:

$.ajax({
     url: "/Home/SaveQBMatter",
     type: "POST",
     data: JSON.stringify({ 'Matters': result, 'originalRecords': originalRecords, 'originalHours': originalHours, 'excludedHours': excludedHours, 'totalHours': totalHours }),
     dataType: "json",
     traditional: true,
     contentType: "application/json; charset=utf-8",
     success: function (data) {
           if (data.status == "Success") {
                var DownloadableFile = data.message;
                //HERE I NEED TO DOWNLOAD FILE
                alert("Success! You will be redirect to the Home Page.");
                var url = '@Url.Action("Index", "Home")';
                window.location.href = url;
           } else {
                alert("Error occurs on the Database level!");
           }
     },
     error: function () {
           alert("An error has occured!!!");
     }
});

data.message中,我从操作SaveQBMatter返回完整文件路径

我需要的只是让我的用户在重定向之前下载这个文件。请帮忙吗?

注意:如果需要此信息,我使用的是ASP.NET MVC。

尝试使用此插件下载文件:http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/

您可以这样做,在成功的ajax调用后,执行location.href=data.message;正如您所说的data.message是文件的完整路径。这样,它就可以在不重定向浏览器的情况下下载文件。此外,当您下载文件时,请确保您具有强制下载的标头。

您可以在此处查看有关强制下载的更多信息:http://www.symkat.com/force-download-with-http-headers

然后,做一个setTimeout,比如说1到2秒,你可以根据自己的喜好调整时间,让下载初始化并重定向。所以你的代码看起来是这样的:

$.ajax({
     url: "/Home/SaveQBMatter",
     type: "POST",
     data: JSON.stringify({ 'Matters': result, 'originalRecords': originalRecords, 'originalHours': originalHours, 'excludedHours': excludedHours, 'totalHours': totalHours }),
     dataType: "json",
     traditional: true,
     contentType: "application/json; charset=utf-8",
     success: function (data) {
           if (data.status == "Success") {
                var DownloadableFile = data.message;
                location.href = DownloadableFile;
                setTimeout(function() {    
                    alert("Success! You will be redirect to the Home Page.");
                    var url = '@Url.Action("Index", "Home")';
                    window.location.href = url;
                }, 1000);
           } else {
                alert("Error occurs on the Database level!");
           }
     },
     error: function () {
           alert("An error has occured!!!");
     }
});

如果用户浏览器未阻止,请尝试在新窗口中打开URL:

if (data.status == "Success") {
    window.open(data.message, "_blank")

如果你在打开文件而不是下载时遇到问题,你可以尝试从ASP发送一个内容处理头,比如:

Content-Disposition: attachment; filename="filename.extension"