Here's the code fragment I'm using now to upload multiple images using HTML5 File API:
/**
* @param {FileList} files
*/
upload: function(files){
nfiles = files.length;
for (var i = 0; i < nfiles; i++) {
/** @var file File **/
var file = files[i];
var xhr = new XMLHttpRequest();
xhr.open("POST", settings.post_upload, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.upload.filenumb = i;
xhr.filenumb = i;
xhr.upload.filename = file.name;
var nef = new FormData();
nef.append("folder", settings.folder);
nef.append("file_element", settings.file_elem);
nef.append("udata", settings.user_data);
nef.append(settings.file_elem, file);
xhr.send(nef);
}
}
I'd like to resize the images before upload using canvas object, but not having experience with this, I'm not sure how can update the code using techniques, e.g. the one described here: HTML5 Pre-resize images before uploading
canvas.toDataURL("image/png");
will return an encoded string. But I need to post the File
object.
Edit
How would you write (reasonably) cross browser function for most modern browsers to resize the File before upload, handling jpg,png and gifs with transparency:
/**
* @param {File} file
* @param int max_width
* @param int max_height
* @param float compression_ratio
* @returns File
*/
function resize(file, max_width, max_height, compression_ratio){}
Try something like this:
Please note:
Working with fileloaders and loading images means there are some delays and the function is therefore asynchronous so trying to simply return the blob data wont work. You need to wait for the loading to occur before you can use the loaded data and fire off a call to your upload function for EACH file.
Also fileloader may have some browser compatability issues but I don't think this is possible any other way client side.
You can call
toBlob
on the<canvas>
element. This will return aBlob
, which is the parent interface ofFile
. You can then send this object to your server via XHR2.Client-side image resize
Option 1. Use the Pica library (https://github.com/nodeca/pica)
Option 2. Use the following custom script (http://jsfiddle.net/cL3hapL4/2/)