Skip to content

Instantly share code, notes, and snippets.

@p2yang
Last active February 12, 2020 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p2yang/72f23f5bd808d424f0b18af34f3c95e1 to your computer and use it in GitHub Desktop.
Save p2yang/72f23f5bd808d424f0b18af34f3c95e1 to your computer and use it in GitHub Desktop.
原生 fetch download file
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
}
}
@p2yang
Copy link
Author

p2yang commented Feb 12, 2020

thanks for the issue comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment