js通过文件的url下载文件到本地

1、iframe

function download(url){
    
    
    var iframe = document.createElement("iframe")
    iframe.style.display = "none";
    iframe.src = url;
    document.body.appendChild(iframe);
}

2、会打开空白页面,下载文件后自动给关闭,用户体验不好

window.open(url)

3、

fetch(url).then(res => res.blob()).then(blob => {
    
     // 将链接地址字符内容转变成blob地址
	  const a = document.createElement('a')
	  a.href = URL.createObjectURL(blob)
	  //测试链接console.log(a.href)
	  a.download = 'fileName'  // 下载文件的名字
	  document.body.appendChild(a)
	  a.click()
})

可参考链接:
1、https://www.zhangxinxu.com/wordpress/2017/07/js-text-string-download-as-html-json-file/
2、https://yugasun.com/post/optimize-download-files-in-frontend.html
3、https://www.cnblogs.com/qingheshiguang/p/15806850.html

猜你喜欢

转载自blog.csdn.net/qq_33235680/article/details/124172789