Last active
February 12, 2020 07:16
-
-
Save p2yang/72f23f5bd808d424f0b18af34f3c95e1 to your computer and use it in GitHub Desktop.
原生 fetch download file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function download (url = '', headers = {}) { | |
try { | |
const res = await fetch(url, { | |
headers | |
}) | |
const blob = await res.blob() | |
// 获取后端headers里面的文件名 | |
const filename = decodeURI(res.headers.get('Content-Disposition').split('filename=')[1]) | |
// download | |
const a = document.createElement('a') | |
a.download = filename | |
a.style.display = 'none' | |
a.href = window.URL.createObjectURL(blob) | |
document.body.appendChild(a) | |
a.click() | |
document.body.removeChild(a) | |
} catch (err) { | |
console.error(err) | |
// toast error message | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for the issue comment