Last active
August 29, 2015 14:16
-
-
Save lovrin/28eaa24f3f5ac46f5db0 to your computer and use it in GitHub Desktop.
In-browser image resize and upload
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 createAndUploadThumbnailImg = function (fileObj) { // i.e., <input type=file> | |
console.log('making thumbnail for...'); | |
console.log(fileObj); | |
var reader = new FileReader(); | |
reader.onload = function (e) { | |
// create canvas obj (<canvas>, not added to DOM) | |
// then give it a reference the URL (not on server; on page) made available by FileReader.readAsDataURL() | |
// then use canvas to draw that image at smaller dimensions, effectively copying and resizing it | |
// | |
var canvas = document.createElement('canvas'); | |
var img = new Image(); | |
img.src = e.target.result; | |
img.onload = function () { | |
canvas.id = "myTempCanvas"; | |
canvas.width = 200; // TODO: calculate proper dimensions | |
canvas.height = 200; | |
if (canvas.getContext) { | |
var cntxt = canvas.getContext("2d"); | |
cntxt.drawImage(img, 0, 0, canvas.width, canvas.height); | |
var dataURL = canvas.toDataURL(); | |
if (dataURL != null && dataURL != undefined) { | |
$('#dacoverimg-thumb').attr('src', dataURL); | |
console.log("thumbnail img displayed"); | |
console.log("... as base64..."); | |
console.log(dataURL); | |
// The secret to getting a proper fileObj (Blob) with mime-type set | |
// is to xhr.get the thumbnail just created, resulting in a | |
// properly-constructed Blob object that can be POST'd using FormData | |
var xhr = new XMLHttpRequest(); | |
xhr.addEventListener('progress', function(){ | |
console.error('progress'); | |
console.log(this); | |
}); | |
xhr.open('GET', dataURL, true); | |
xhr.responseType = 'blob'; | |
xhr.onload = function(e) { | |
console.log('grabbed thumbnail via URL...'); | |
console.log(this); | |
var formData = new FormData(); | |
formData.append('file', this.response); // optional 3rd param: filename | |
$.ajax({ | |
url: serverURL, | |
type: "POST", | |
data: formData, | |
processData: false, | |
contentType: false | |
}) | |
}; | |
xhr.send(); | |
} | |
else { | |
alert('unable to get context'); | |
} | |
} | |
} | |
}; | |
reader.readAsDataURL(fileObj); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
only works in firefox as of Feb 28 2015...