Created
March 24, 2015 22:11
-
-
Save talves/57a750543373a699c8cc to your computer and use it in GitHub Desktop.
Blob vs FileUpload
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
<input type="file" id="fileInput" /> | |
<div id="fileDisplayArea"></div> |
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
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