Created
September 8, 2018 03:54
-
-
Save kelvearagao/9dc6cb4ff066fca1fd6b74707424fbe5 to your computer and use it in GitHub Desktop.
Realizando download via javascript!
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>testing download</title> | |
</head> | |
<body> | |
<h1>testing download</h1> | |
<button onclick="fetch('GET', 'http://127.0.0.1:8080/public/downloads.zip', true)">new version</button> | |
<br><br> | |
<button onclick="fetch('GET', 'http://127.0.0.1:8080/public/downloads.zip', false)">old version</button> | |
<script> | |
console.log('--> testing download', new Date()); | |
const forceDownload = (blob, filename) => { | |
const urlCreator = window.URL || window.webkitURL | |
let link = document.createElement('a'); | |
link.href = urlCreator.createObjectURL(blob); | |
link.download = filename; | |
link.click(); | |
urlCreator.revokeObjectURL(link.href); | |
} | |
const binStrToBlob = (binStr, type) => | |
new Blob([ Uint8Array.from(binStr.split(''), c => c.charCodeAt()) ], { type }); | |
const fetch = (method, url, newVersion) => { | |
let request = new XMLHttpRequest(); | |
if (newVersion) { | |
request.responseType = 'blob'; | |
} else { | |
request.overrideMimeType('text/plain; charset=x-user-defined'); | |
} | |
request.open(method, url) | |
request.onload = function() { | |
const blob = newVersion ? | |
this.response : binStrToBlob(this.response, this.getResponseHeader('content-type')) | |
console.log('--> result', this); | |
console.log('--> blob', blob); | |
forceDownload(blob, 'teste.zip') | |
}; | |
request.send(); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment