1、form表单下载文件
function downloadFile(url){
var form=$("<form>");//定义form表单,通过表单发送请求
form.attr("style","display:none");//设置为不显示
form.attr("target","");
form.attr("method","get");//设置请求类型
form.attr("action",url);//设置请求路径
$("body").append(form);//添加表单到页面(body)中
form.submit();//表单提交
}
2、iframe下载文件
function downloadFile(url) {
try{
var elemIF = document.createElement("iframe");
elemIF.src = url;
elemIF.style.display = "none";
document.body.appendChild(elemIF);
}catch(e){
}
}
3、链接下载文件
<a href=”file.js”>file.js</a>
//该方法火狐有些版本是不支持的
window.location.href="htpp://www.baidu.com/test.rar"
//为了解决火狐有些版本不支持,可以改成这种方式
window.location="htpp://www.baidu.com/test.rar";
//该方法在火狐上没有效果的,在IE浏览器上是可以的
window.open("htpp://www.baidu.com/test.rar")
4、ajax下载文件
function saveFile(url) {
return new Promise(function(resolve, reject) {
// Get file name from url.
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
resolve(xhr);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.send();
}).then(function(xhr) {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
a.download = filename; // Set the file name.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
return xhr;
});
}
前后端分离下载文件的方法
最新推荐文章于 2024-08-09 02:10:38 发布