HTML5 AJAX File Upload
timdream
Tossug, Sep. 14, 2010
AJAX File Upload
:(
HTML5 come to the rescue!
:)
Steps to send a file
1. Receive Files from User
$('input[type=file]').bind('change',� function () {
handleFile(this.files[0]);
}
);
$('div')�.bind('dragover',function () {return false;})�.bind('drop',function (ev) { � handleFile(� ev.originalEvent.dataTransfer.files[0]� );
});
2. Read the File
var reader = new FileReader();
reader.onloadend = function (ev) {
var bin = ev.target.result;
};
reader.onerror = function (ev) {
switch (ev.target.error) { ... }
};
reader.readAsBinaryString(file);
3. Construct request body
--boundary-103973
content-disposition: form-data; name="Filedata"; filename="a-image.png"
Content-Type: image/png
%PNG
IHDR��........(binary string)
--boundary-103973--
3. Construct request body (cont.)
var formdata = new FormData();
formdata.append('Filedata', file);
4. Send the file through xhr
Comparison & Small Conclusion
Browser Read Form Send
Fx 3.0/3.5 readAsBinary() self-craft sendAsBinary()
Fx 3.6 FileReader self-craft sendAsBinary()
Fx 4 FormData FormData send(formdata)
Chrome 5 FormData FormData send(formdata)
Safari 5 FormData FormData send(formdata)
Opera 10.6 Not supported Yet
IE Wheeeee!!!!
Issue: UTF-8 file name
var encString = encodeURIComponent('土虱.png');
//'%E5%9C%9F%E8%99%B1.png'
String.fromCharCode(parseInt('E5', 16));
//'å': U+00E5, 0xE5 in ASCII
...
//åÉŸè™±.png
Issue: Feature Detection
Browser Read Form Send
Fx 3.0/3.5 readAsBinary() self-craft sendAsBinary()
Fx 3.6 FileReader self-craft sendAsBinary()
Fx 4 FormData FormData send(formdata)
Chrome 5 FormData FormData send(formdata)
Safari 5 FormData FormData send(formdata)
if (
(XMLHttpRequest && XMLHttpRequest.prototype.sendAsBinary)
|| window.FormData
) { $(document.body).addClass('support_ajaxfileupload'); }
Issue: Pre-processing
Issue: jQuery.ajax() integration
Issue: jQuery.ajax integration (cont.)
settings.contentType = null;
settings.data = null;�settings.__beforeSend = settings.beforeSend;�settings.beforeSend = function (xhr, s) {� s.data = formdata;� if (s.__beforeSend)
return s.__beforeSend.call(this, xhr, s);�}
Issue: jQuery.ajax integration (cont.)
XMLHttpRequest.prototype.send = function (data) {� return this.sendAsBinary(data);�}
settings.___beforeSend = settings.beforeSend;�settings.beforeSend = function (xhr, s) {� xhr.send = xhr.sendAsBinary;� if (s.___beforeSend) return s.___beforeSend.call(this, xhr, s);�}�
(faint)
因為全部搞定實在是太麻煩了
I made a jQuery plug-in for everything above.
(dance)
Issue: Interaction
Demo
http://timc.idv.tw/html5-file-upload/
Acknowledgment
Q & A
Thank you