Last active
March 21, 2018 11:06
-
-
Save vladimir-ivanov/359ce8257e7d9fbcf696074288c490d7 to your computer and use it in GitHub Desktop.
example of file upload, conversion to blob and then download
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
<html> | |
<head> | |
<style> | |
div { | |
margin: 20px; | |
} | |
</style> | |
</head> | |
<body> | |
<input type="file" id="your-files" multiple> | |
<script> | |
let input = document.querySelector('input[type=file]'); | |
function readFile(event) { | |
console.info('reading file ok', event.target.result); | |
const data = event.target.result; | |
const fileName = 'my-download.pdf'; | |
saveData(data, fileName); | |
} | |
const changeFile = () => { | |
let file = input.files[0]; | |
let reader = new FileReader(); | |
reader.addEventListener('load', readFile); | |
reader.readAsDataURL(file); | |
}; | |
const saveData = (data, fileName) => { | |
let a = document.createElement('a'); | |
document.body.appendChild(a); | |
a.style = 'display: none'; | |
console.warn(fileName); | |
fetch(data).then(res => res.blob()).then(blob => { | |
url = window.URL.createObjectURL(blob); | |
a.href = url; | |
a.download = fileName; | |
a.click(); | |
console.warn(url); | |
window.URL.revokeObjectURL(url); | |
document.body.removeChild(a); | |
}); | |
}; | |
input.addEventListener('change', changeFile); | |
</script> | |
</code> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment