SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
HTML5 AJAX File Upload
timdream
Tossug, Sep. 14, 2010
AJAX File Upload
The ability to send files from browser to server without
whole-page form submission
Demand exists ever since rich web app. was being
developed (circa. 2004)
People tried to do this by other means
Flash-based resolution, e.g. SWFUpload
Flash sucks on non-IE browsers (NPAPI version)
Even sucks more on iOS
iframe and a form
Breaks back/forward buttons
Compromised program workflow
Doesn't show progress (except Chrome)
:(
HTML5 come to the rescue!
:)
Steps to send a file
1. Receive file from user
through <input type="file" />, or
File dropping
2. Read the file
3. Construct RFC 1867 multipart/form-data request body
or, not exactly
4. Send the file through XMLHttpRequest
1. Receive Files from User
or, getting the FileList and File object
$('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
Filefox 3.0+: var bin = file.getAsBinary();
Might block UI
Might throw error
Firefox 3.6
var reader = new FileReader();
reader.onloadend = function (ev) {
var bin = ev.target.result;
};
reader.onerror = function (ev) {
switch (ev.target.error) { ... }
};
reader.readAsBinaryString(file);
Firefox 4, Chrome 5, Safari 5: Skip this step
3. Construct request body
Body of a POST request, defined in RFC 1867
--boundary-103973
content-disposition: form-data; name="Filedata"; filename="a-image.png"
Content-Type: image/png
%PNG
IHDR��........(binary string)
--boundary-103973--
We need to craft our own if there is no FormData
Firefox 3.0, Firefox 3.5, Firefox 3.6
UTF-8 file name issue
3. Construct request body (cont.)
For browsers provide FormData
var formdata = new FormData();
formdata.append('Filedata', file);
4. Send the file through xhr
For FormData Browsers: xhr.send(formdata);
Most leave automatically generated Content-Type
header alone
For self-crafted binary string request body (as data):
xhr.sendAsBinary(data);
Most specify content-type along with request body, e.g.
multipart/form-data, boundary=boundary-103973
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
Only applied to self-crafted request body
Solution: conversion UTF-8 filename to binary string
ourselves
encodeURIComponent() could to the trick
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)
Anything marked in red cannot be detected.
Detection based on existence of FileList or File won't
work.
Solution: come up an if (expression) {} based on this
table.
if (
(XMLHttpRequest && XMLHttpRequest.prototype.sendAsBinary)
|| window.FormData
) { $(document.body).addClass('support_ajaxfileupload'); }
Issue: Pre-processing
Case: Thumbnail an image before sending it
Can be done with FileReader or getAsBinary
Won't work with FormData cause File is read-only and
cannot be constructed.
Workaround
rewrite server endpoint for it to receive files as form
fields or even request body itself
convert the data into base64 string so it would go
through xhr.send()
Any suggestions?
Issue: jQuery.ajax() integration
Benefit: to have jQuery
call global ajax event handler
process the response data (with preferred dataType)
Problems: jQuery is too smart sometimes
it defaults request content type to
application/x-www-form-urlencoded,
but we need content-type being
multipart/form-data, boundary=boundary-103973
it converts post data from object to string if it's an object
Wait! FormData is an object!
jQuery hard-coded xhr.send()
But we need xhr.sendAsBinary()
Issue: jQuery.ajax integration (cont.)
Solution for content-type overwrite and data conversion
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);
}
based on jQuery-1.4.2.js line 5119
Only needed if you are using FormData
Issue: jQuery.ajax integration (cont.)
Solution for hard-coded xhr.send()
XMLHttpRequest.prototype.send = function (data) {
return this.sendAsBinary(data);
}
DO NOT USE sendAsBinary with FormData
Use sendAsBinary to send ASCII string appears fine
Alternatively,
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
For file input control
Some CSS hack could overwrite the default look
Do disable and provide alternative when the browser is
not supported
For drag and drop control
Do provide visual indication when file is being dragging
over the page
Do disable indication above (or any instruction before file
being dragged into) if the browser don't support
uploading
For AJAX Uploading
Do provide an indicator
Progress is only supported by Firefox (for now)
Demo
http://timc.idv.tw/html5-file-upload/
Acknowledgment
jnlin
othree for this tweet
Tossug
Q& A
Thank you

Contenu connexe

Tendances

Tendances (20)

Ado.net
Ado.netAdo.net
Ado.net
 
World wide web architecture presentation
World wide web architecture presentationWorld wide web architecture presentation
World wide web architecture presentation
 
Internet and Web Technology (CLASS-2) [HTTP & HTML]
Internet and Web Technology (CLASS-2) [HTTP & HTML]Internet and Web Technology (CLASS-2) [HTTP & HTML]
Internet and Web Technology (CLASS-2) [HTTP & HTML]
 
12th computer-application-unit-8-study-material-english-medium
12th computer-application-unit-8-study-material-english-medium12th computer-application-unit-8-study-material-english-medium
12th computer-application-unit-8-study-material-english-medium
 
Database Connection
Database ConnectionDatabase Connection
Database Connection
 
An Overview of Entity Framework
An Overview of Entity FrameworkAn Overview of Entity Framework
An Overview of Entity Framework
 
Dom Hackking & Security - BlackHat Preso
Dom Hackking & Security - BlackHat PresoDom Hackking & Security - BlackHat Preso
Dom Hackking & Security - BlackHat Preso
 
Comp102 lec 11
Comp102   lec 11Comp102   lec 11
Comp102 lec 11
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
Visual basic databases
Visual basic databasesVisual basic databases
Visual basic databases
 
File
FileFile
File
 
php databse handling
php databse handlingphp databse handling
php databse handling
 
15. session 15 data binding
15. session 15   data binding15. session 15   data binding
15. session 15 data binding
 
Le Wagon - Web 101
Le Wagon - Web 101Le Wagon - Web 101
Le Wagon - Web 101
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
Using Webservice in iOS
Using Webservice  in iOS Using Webservice  in iOS
Using Webservice in iOS
 
ETH Zurich's DOI Desk
ETH Zurich's DOI DeskETH Zurich's DOI Desk
ETH Zurich's DOI Desk
 
Database driven web pages
Database driven web pagesDatabase driven web pages
Database driven web pages
 
Uniform Resource Locator (URL)
Uniform Resource Locator (URL)Uniform Resource Locator (URL)
Uniform Resource Locator (URL)
 
Dom
DomDom
Dom
 

Similaire à HTML5 AJAX File Upload

Asp.net By Durgesh Singh
Asp.net By Durgesh SinghAsp.net By Durgesh Singh
Asp.net By Durgesh Singhimdurgesh
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 
Cliw - extension development
Cliw -  extension developmentCliw -  extension development
Cliw - extension developmentvicccuu
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Adnan Sohail
 
Dojo - from web page to web apps
Dojo - from web page to web appsDojo - from web page to web apps
Dojo - from web page to web appsyoavrubin
 
AJAX
AJAXAJAX
AJAXARJUN
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptxitzkuu01
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-frameworkSakthi Bro
 
Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a BottleZohar Arad
 
file-transfer-using-tcp.pdf
file-transfer-using-tcp.pdffile-transfer-using-tcp.pdf
file-transfer-using-tcp.pdfJayaprasanna4
 

Similaire à HTML5 AJAX File Upload (20)

Browser Security
Browser SecurityBrowser Security
Browser Security
 
Php BASIC
Php BASICPhp BASIC
Php BASIC
 
AJAX
AJAXAJAX
AJAX
 
Play framework
Play frameworkPlay framework
Play framework
 
Asp.net By Durgesh Singh
Asp.net By Durgesh SinghAsp.net By Durgesh Singh
Asp.net By Durgesh Singh
 
Lec 7
Lec 7Lec 7
Lec 7
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
Beyond the page
Beyond the pageBeyond the page
Beyond the page
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
Cliw - extension development
Cliw -  extension developmentCliw -  extension development
Cliw - extension development
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
 
RIA and Ajax
RIA and AjaxRIA and Ajax
RIA and Ajax
 
Dojo - from web page to web apps
Dojo - from web page to web appsDojo - from web page to web apps
Dojo - from web page to web apps
 
AJAX
AJAXAJAX
AJAX
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-framework
 
Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a Bottle
 
file-transfer-using-tcp.pdf
file-transfer-using-tcp.pdffile-transfer-using-tcp.pdf
file-transfer-using-tcp.pdf
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 

Plus de Timothy Chien

Insight Gaia - OS Shell in a &lt;html>
Insight Gaia - OS Shell in a &lt;html>Insight Gaia - OS Shell in a &lt;html>
Insight Gaia - OS Shell in a &lt;html>Timothy Chien
 
Apps on HTML5 - Why, how, and beyond
Apps on HTML5 - Why, how, and beyondApps on HTML5 - Why, how, and beyond
Apps on HTML5 - Why, how, and beyondTimothy Chien
 
Gfx.tw: Two Year Report
Gfx.tw: Two Year ReportGfx.tw: Two Year Report
Gfx.tw: Two Year ReportTimothy Chien
 
HTML5 應用程式開發簡介
HTML5 應用程式開發簡介HTML5 應用程式開發簡介
HTML5 應用程式開發簡介Timothy Chien
 
Google Apps Account as OpenID (中文)
Google Apps Account as OpenID (中文)Google Apps Account as OpenID (中文)
Google Apps Account as OpenID (中文)Timothy Chien
 
Google Apps Account as OpenID
Google Apps Account as OpenIDGoogle Apps Account as OpenID
Google Apps Account as OpenIDTimothy Chien
 
OpenID 登入 UI 與流程設計
OpenID 登入 UI 與流程設計OpenID 登入 UI 與流程設計
OpenID 登入 UI 與流程設計Timothy Chien
 

Plus de Timothy Chien (7)

Insight Gaia - OS Shell in a &lt;html>
Insight Gaia - OS Shell in a &lt;html>Insight Gaia - OS Shell in a &lt;html>
Insight Gaia - OS Shell in a &lt;html>
 
Apps on HTML5 - Why, how, and beyond
Apps on HTML5 - Why, how, and beyondApps on HTML5 - Why, how, and beyond
Apps on HTML5 - Why, how, and beyond
 
Gfx.tw: Two Year Report
Gfx.tw: Two Year ReportGfx.tw: Two Year Report
Gfx.tw: Two Year Report
 
HTML5 應用程式開發簡介
HTML5 應用程式開發簡介HTML5 應用程式開發簡介
HTML5 應用程式開發簡介
 
Google Apps Account as OpenID (中文)
Google Apps Account as OpenID (中文)Google Apps Account as OpenID (中文)
Google Apps Account as OpenID (中文)
 
Google Apps Account as OpenID
Google Apps Account as OpenIDGoogle Apps Account as OpenID
Google Apps Account as OpenID
 
OpenID 登入 UI 與流程設計
OpenID 登入 UI 與流程設計OpenID 登入 UI 與流程設計
OpenID 登入 UI 與流程設計
 

Dernier

How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 

Dernier (20)

How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 

HTML5 AJAX File Upload

  • 1. HTML5 AJAX File Upload timdream Tossug, Sep. 14, 2010
  • 2. AJAX File Upload The ability to send files from browser to server without whole-page form submission Demand exists ever since rich web app. was being developed (circa. 2004) People tried to do this by other means Flash-based resolution, e.g. SWFUpload Flash sucks on non-IE browsers (NPAPI version) Even sucks more on iOS iframe and a form Breaks back/forward buttons Compromised program workflow Doesn't show progress (except Chrome) :(
  • 3. HTML5 come to the rescue! :)
  • 4. Steps to send a file 1. Receive file from user through <input type="file" />, or File dropping 2. Read the file 3. Construct RFC 1867 multipart/form-data request body or, not exactly 4. Send the file through XMLHttpRequest
  • 5. 1. Receive Files from User or, getting the FileList and File object $('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] ); });
  • 6. 2. Read the File Filefox 3.0+: var bin = file.getAsBinary(); Might block UI Might throw error Firefox 3.6 var reader = new FileReader(); reader.onloadend = function (ev) { var bin = ev.target.result; }; reader.onerror = function (ev) { switch (ev.target.error) { ... } }; reader.readAsBinaryString(file); Firefox 4, Chrome 5, Safari 5: Skip this step
  • 7. 3. Construct request body Body of a POST request, defined in RFC 1867 --boundary-103973 content-disposition: form-data; name="Filedata"; filename="a-image.png" Content-Type: image/png %PNG IHDR��........(binary string) --boundary-103973-- We need to craft our own if there is no FormData Firefox 3.0, Firefox 3.5, Firefox 3.6 UTF-8 file name issue
  • 8. 3. Construct request body (cont.) For browsers provide FormData var formdata = new FormData(); formdata.append('Filedata', file);
  • 9. 4. Send the file through xhr For FormData Browsers: xhr.send(formdata); Most leave automatically generated Content-Type header alone For self-crafted binary string request body (as data): xhr.sendAsBinary(data); Most specify content-type along with request body, e.g. multipart/form-data, boundary=boundary-103973
  • 10. 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!!!!
  • 11. Issue: UTF-8 file name Only applied to self-crafted request body Solution: conversion UTF-8 filename to binary string ourselves encodeURIComponent() could to the trick var encString = encodeURIComponent('土虱.png'); //'%E5%9C%9F%E8%99%B1.png' String.fromCharCode(parseInt('E5', 16)); //'å': U+00E5, 0xE5 in ASCII ... //åÉŸè™±.png
  • 12. 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) Anything marked in red cannot be detected. Detection based on existence of FileList or File won't work. Solution: come up an if (expression) {} based on this table. if ( (XMLHttpRequest && XMLHttpRequest.prototype.sendAsBinary) || window.FormData ) { $(document.body).addClass('support_ajaxfileupload'); }
  • 13. Issue: Pre-processing Case: Thumbnail an image before sending it Can be done with FileReader or getAsBinary Won't work with FormData cause File is read-only and cannot be constructed. Workaround rewrite server endpoint for it to receive files as form fields or even request body itself convert the data into base64 string so it would go through xhr.send() Any suggestions?
  • 14. Issue: jQuery.ajax() integration Benefit: to have jQuery call global ajax event handler process the response data (with preferred dataType) Problems: jQuery is too smart sometimes it defaults request content type to application/x-www-form-urlencoded, but we need content-type being multipart/form-data, boundary=boundary-103973 it converts post data from object to string if it's an object Wait! FormData is an object! jQuery hard-coded xhr.send() But we need xhr.sendAsBinary()
  • 15. Issue: jQuery.ajax integration (cont.) Solution for content-type overwrite and data conversion 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); } based on jQuery-1.4.2.js line 5119 Only needed if you are using FormData
  • 16. Issue: jQuery.ajax integration (cont.) Solution for hard-coded xhr.send() XMLHttpRequest.prototype.send = function (data) { return this.sendAsBinary(data); } DO NOT USE sendAsBinary with FormData Use sendAsBinary to send ASCII string appears fine Alternatively, settings.___beforeSend = settings.beforeSend; settings.beforeSend = function (xhr, s) { xhr.send = xhr.sendAsBinary; if (s.___beforeSend) return s.___beforeSend.call(this, xhr, s); }
  • 18. I made a jQuery plug-in for everything above. (dance)
  • 19. Issue: Interaction For file input control Some CSS hack could overwrite the default look Do disable and provide alternative when the browser is not supported For drag and drop control Do provide visual indication when file is being dragging over the page Do disable indication above (or any instruction before file being dragged into) if the browser don't support uploading For AJAX Uploading Do provide an indicator Progress is only supported by Firefox (for now)