从jquery下载具有现有路径的文件的最简单方法
The simplest way to download file with existing path from jquery?
我浏览了十几页,提出了"如何从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"
相关文章:
- JQuery:向多个匹配结果添加换行符的最简单方法
- 访问对象的最简单方法'的单独财产
- Grunt-将多个文件最小化/处理为一个文件
- 在Scroll上更新CSS代码:简化它就不会了'不要使用JQuery和最简单的Javascript
- 什么'这是使用jQuery将一些文本锚定到外部链接的最简单方法
- 什么是处理JavaScript的最简单的网络抓取工具
- 实施会员系统的最简单方法是什么
- 从jquery下载具有现有路径的文件的最简单方法
- 将javascript添加到200多个html文件中,最简单的方法
- 尽可能创建最简单的typescript定义文件
- 上传Html 5拖放文件的最简单方法
- 最简单的ajax (jQuery)版本,只上传一个文件
- 最简单的方法是用JavaScript读/写一个小的JSON文件
- What's是使用JavaScript和jQuery为待办事项网站创建用户配置文件的最好和最简单的方法
- 用Chrome文件接口写文件最简单的方法是什么?
- 将文件链接到Javascript程序的最简单方法是什么?
- .js文件是保存可变数据的最简单方法吗?
- 使用 express 提供静态文件的最简单方法是什么?
- 在实时网页上执行JavaScript文件的最快、最简单的方法是什么?
- 获取服务器目录中文件列表的最简单方法