情景:直接前端下載圖片、pdf、mp4等文件,沒有和后端交互。
常見用法:a鏈接加download屬性
<a download="">下載</a>
問題:有些cdn上的圖片、文件不能直接下載,直接打開。
解決方案:
<div onclick="handleDownload('https://cdnxxxx.com/activity/load.pdf')">下載</div>
<script>
function handleDownload(str) {
const name = "附件";
const url = str;
const suffix = url.substring(url.lastIndexOf("."), url.length);
const x = new XMLHttpRequest();
x.open("GET", url, true);
x.responseType = 'blob';
x.onload=function(e) {
const url = window.URL.createObjectURL(x.response);
const a = document.createElement('a');
a.href = url;
a.download = name + suffix;
a.click()
};
x.send();
}
</script>
ps:該方法實(shí)驗(yàn)了一部分,如有失效的時(shí)候,歡迎指出。