Skip to content

Instantly share code, notes, and snippets.

@jiangtao
Created May 16, 2020 12:13
Show Gist options
  • Save jiangtao/60c374f2f4782a24d86ec1f91cf9b662 to your computer and use it in GitHub Desktop.
Save jiangtao/60c374f2f4782a24d86ec1f91cf9b662 to your computer and use it in GitHub Desktop.
download any file in broswer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="btn" >download</div>
<script>
function blobDownload (filepath, fileName) {
console.log(filepath, fileName)
let xhr = new XMLHttpRequest()
xhr.open('GET', filepath, true)
xhr.responseType = 'arraybuffer'
xhr.addEventListener('progress', function(event) {
if (event.lengthComputable) {
var percentComplete = event.loaded / event.total * 100;
console.log(percentComplete);
}
})
xhr.onload = function() {
console.log('xxx')
if (this.status === 200) {
let type = xhr.getResponseHeader('Content-Type')
let blob = new Blob([this.response], {type: type})
if (typeof window.navigator.msSaveBlob !== 'undefined') {
/*
* IE workaround for "HTML7007: One or more blob URLs were revoked by closing
* the blob for which they were created. These URLs will no longer resolve as
* the data backing the URL has been freed."
*/
window.navigator.msSaveBlob(blob, fileName)
} else {
let URL = window.URL || window.webkitURL
let objectUrl = URL.createObjectURL(blob)
if (fileName) {
var a = document.createElement('a')
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = objectUrl
} else {
a.href = objectUrl
a.download = fileName
document.body.appendChild(a)
a.click()
a.remove()
}
} else {
window.location = objectUrl
}
}
}
}
xhr.send()
}
function download() {
console.log('downlod')
const pdfUrl = 'https://hexyun.oss-cn-beijing.aliyuncs.com/cloud_expo_5eb6152d14b7b129cf44ec71/1589614759580/c847e339f224406b501aa914ddb63115.pdf';
const zipUrl = 'https://hexyun.oss-cn-beijing.aliyuncs.com/cloud_expo_5eb6152d14b7b129cf44ec71/1589613164172/736f70c83dd51df59eb5b24bc4448a01.zip';
const imgUrl = 'https://hexyun.oss-cn-beijing.aliyuncs.com/cloud_expo_5eb6152d14b7b129cf44ec71/1589595760894/c1a675b5f7a67366a0c580556835b6a4.jpg?x-oss-process=image/resize,w_200';
blobDownload(imgUrl, 'c1a675b5f7a67366a0c580556835b6a4.jpg')
}
document.querySelector('#btn').addEventListener('click', download)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment