Skip to content

Instantly share code, notes, and snippets.

@talves
Created March 24, 2015 22:11
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 talves/57a750543373a699c8cc to your computer and use it in GitHub Desktop.
Save talves/57a750543373a699c8cc to your computer and use it in GitHub Desktop.
Blob vs FileUpload
<input type="file" id="fileInput" />
<div id="fileDisplayArea"></div>
var fileInput= document.getElementById('fileInput');
var fileDisplayArea= document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(){
console.log('ran');
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
// Create a new image.
var img = new Image();
// Set the img src property using the data URL.
img.src = reader.result;
// Add the image to the page.
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!";
}
});
window.URL = window.URL || window.webkitURL; // Take care of vendor prefixes.
var xhr = new XMLHttpRequest();
console.log('has CORS',("withCredentials" in xhr));
xhr.open('GET', 'http://i.imgur.com/Ar1SBEH.png', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
console.log(blob);
var img = document.createElement('img');
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // Clean up after yourself.
};
img.src = window.URL.createObjectURL(blob);
fileDisplayArea.appendChild(img);
}
};
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment