Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Last active June 27, 2023 03:36
Show Gist options
  • Save nolanlawson/62e747cea7af01542479 to your computer and use it in GitHub Desktop.
Save nolanlawson/62e747cea7af01542479 to your computer and use it in GitHub Desktop.
File input to Blob example
<html>
<head>
<style>
div {
margin: 20px;
}
</style>
</head>
<body>
<h1>Convert file input to Blob</h1>
<div>
<label for="load-file">Load a file:</label>
<input type="file" id="load-file">
</div>
<div>
<label for="file-type">File type: </label>
<input type="text" id="file-type" value="image/png">
</div>
<div>
<button type="button" id="done-button">Convert to Blob (look in the console)</button>
</div>
<script src="https://unpkg.com/[email protected]/dist/blob-util.js"></script>
<script>
var $ = document.querySelector.bind(document)
$('#done-button').addEventListener('click', function (e) {
var file = $('#load-file').files[0];
var fileReader = new FileReader();
fileReader.onloadend = function (e) {
var arrayBuffer = e.target.result;
var fileType = $('#file-type').value;
var blob = blobUtil.arrayBufferToBlob(arrayBuffer, fileType)
console.log('here is a blob', blob);
console.log('its size is', blob.size);
console.log('its type is', blob.type);
};
fileReader.readAsArrayBuffer(file);
});
</script>
</body>
</html>
@luludada
Copy link

Hi Nolan, I just tested your demo recently, but I got the error: Uncaught TypeError: blobUtil.arrayBufferToBlob(...).then is not a function at FileReader.fileReader.onloadend, but I am not sure why.

@FocSon
Copy link

FocSon commented Jun 6, 2021

Same here

@nolanlawson
Copy link
Author

Fixed it. Note though that converting a File to a Blob is useless, because a File is a Blob. https://developer.mozilla.org/en-US/docs/Web/API/File

This was probably something I did not know when I first wrote this 6 years ago. 🙂

@FocSon
Copy link

FocSon commented Jun 7, 2021

Ho i didn't know that .. Thank you very much !

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