场景使用&解释
通过ajax请求是否符合下载文件,并且获取ajax返回的文件链接进行下载操作代码。
代码串
/**
* @name uxdown(file) 下载文件
* @author flower
* @mtime 2022-10-14
* @param file string
* @return file
*/
function uxdown(file)
{
var URLToPDF = file;
var theFileName = URLToPDF.substring(URLToPDF.lastIndexOf('/') + 1, URLToPDF.length);
var URL = window.URL || window.webkitURL;
var oReq = new XMLHttpRequest();
oReq.open("GET", URLToPDF, true);
oReq.responseType = "blob";
oReq.onload = function() {
var file = new Blob([oReq.response], {
type: 'application/pdf'
});
saveAs(file, theFileName);
};
oReq.send();
}
function saveAs(blob, filename) {
var type = blob.type;
var force_saveable_type = 'application/octet-stream';
if (type && type != force_saveable_type) {
var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
}
var url = URL.createObjectURL(blob);
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = url;
save_link.download = filename;
var event = new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window
});
save_link.dispatchEvent(event);
URL.revokeObjectURL(url);
}
版权声明:本文为原创文章,版权归 星环博客 所有,转载请注明出处!
本文链接: https://xhto.cn/archives/251.html
友情提示:添加友联和友联失效404的请联系博主,并确保自己网站已经添加博主为友联!
黑色的背后是黎明... + 赞赏博主吧!已经穷的开不起站了~