HTML5 asynchronous file upload

Source: Internet
Author: User

HTML5 asynchronous file upload

Recently, companies want to use Image Upload for mobile websites. Mobile phones generally do not use flash upload tools like swfupload (poor support for flash) however, mobile browsers now support HTML5, so I checked it online over the past few days to upload files using html5.


In fact, it is quite simple to upload files in html5, directly new FormData (); this is based on the new API of XMLHttpRequest 2.

You can create an empty FormData object, and then use the append () method to add fields to the object, as shown below:

<Script type = "text/javascript"> var oMyForm = new FormData (); oMyForm. append ("username", "Groucho"); oMyForm. append ("accountnum", 123456); // The number 123456 is immediately converted to the string "123456" // fileInputElement contains the file oMyForm selected by the user. append ("userfile", document. elementById ('file '). files [0]); oMyForm. append ("webmasterfile", oBlob); var oReq = new XMLHttpRequest (); oReq. open ("POST", "_ URL _/api/upload"); oReq. send (oMyForm); </script>

This allows you to upload files to the backend.

Of course, you can also set the accept attribute for only uploading images in the file.

 

If you use jquery, you can also implement it in jquery.

Vm. save = function () {var data = new FormData (); data. append ('A _ id', model. a_id); data. append ('name', model. name); data. append ('sort ', model. sort); data. append ('file', $ ('# aaa') [0]. files [0]); $. ajax ({url: '_ URL _/picsave', type: 'post', data: data, processData: false, // tell jQuery not to process the sent data contentType: false // tell jQuery not to set the Content-Type Request Header }). done (function (ret) {if (ret) {alert (ret);} else {aler T ('saved successfully! '); // Location =' _ URL _ ';}); return false ;};



Let's talk about this today and continue to be busy.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.