How to upload images using JavaScript

Source: Internet
Author: User
Before XMLHttpRequestLevel2 was introduced, most asynchronous images were uploaded using iframe. As for the specific implementation details, I am not here ?? Module? Oogle has an article to talk about. This time I will talk about how to use a new API to upload images. First,... SyntaxHighlighter. all (before XMLHttpRequest Level2 was introduced, most asynchronous upload images were implemented using iframe. As for the specific implementation details, I am not here ?? Module? Oogle has an article to talk about. This time I will talk about how to use a new API to upload images. First, some new features of XMLHttpRequest Level2 are indispensable. The most practical one is the FormData object, which directly converts the Dom object of form into a FormData object and then sends it to the server. There is also the support for the Progress event. asynchronous upload can finally view the Progress bar! I won't talk nonsense here, because most people should have read Ruan Yifeng's XMLHttpRequest Level 2 User Guide and paste the Code directly. 1 var formData = new FormData (form), 2 xhr = new XMLHttpRequest (); 3 4 xhr. open ("POST", url); 5 xhr. send (formData); the interface is also very simple, such as PHP, you can directly use $ _ POST, $ _ FILES to get the relevant data. that's all. By listening to the SS time, you can determine the Progress of the current data upload/download. 1 xhr. upload. onprogress = function (e) {2 console. log (e. loaded/e. total * 100); // upload progress 3} 4 5 xhr. onprogress = function (e) {6 console. log (e. loaded/e. total * 100); // download progress 7} As for XMLHttpRequest Level2 support, it is ideal on the Mobile End. For a long time, countless front-ends? Pan yiqichan? A href =" http://www.2cto.com/os/liulanqi/ "Target =" _ blank "class =" keylink "> the browser provides APIs for JavaScript to access local files. In fact, IE was able to use ActiveX to operate local files as early as possible, but since it is not W3C standard, it has always been just IE. At 25 October 2012, W3C entered into a draft File API. In addition, FileReader objects are used together with File objects. The specific usage will be discussed later. The following is their support, which is generally the case. But it's almost the same as learning it first ~ Let's talk about the File object first. The File object is from the user in The FileList object returned after the file is selected on the element. It can also be a DataTransfer object generated by the drag-and-drop operation. 1 // input: file object 2 document. querySelector ("input [type = file]"). files; // return FileList3 4 // drop Event File object 5 elem. ondrop = function (e) {6 e. preventDefault (); 7 return e. dataTransfer. files; // return FileList8}; are returned as a FileList object. The FileList object is similar to NodeList. It has the length attribute, but is not an array. The following is the FileList object printed by Chrome Console: Let's take a look at the attributes of the File object: What do these attributes mean. However, we can note that the File object inherits from the Blob Object. As for what is a Blob object, we will refer to it later. In the beginning, we also mentioned a FileReader object, which is used together with a File object. With the FileReader object, web applications can asynchronously read files (or raw data buffering) stored on users' computers, you can use a File object or Blob Object to specify the File or data to be read. for more information, see the following code: 1 // create a FileReader object 2 var reader = new FileReader (); 3 4 // bind the load event 5 reader. onload = function (e) {6 lele.log(e.tar get. result); 7} 8 9 // read the data of the File object 10 reader. readAsDataURL (document. querySelector ("input [type = file]"). files [0]); when the FileReader object reads data through readAsDataURL, the load event is triggered. The value of the result attribute in target is the base64 data of the file. Of course, the FileReader object is not just a readAsDataURL method. 1/*** abort the read operation. when returned, the value of the readyState attribute is DONE. 3 */4 reader. abort (); 5 6 7/** 8 * start to read the content of the specified Blob Object or File object. 9 * When the read operation is complete, the value of the readyState attribute becomes DONE. If the onloadend event handler is set, it is called. 10 * at the same time, the result attribute will contain a string in the data: URL format to indicate the content of the file to be read. 11 */12 reader. readAsDataURL (file); 13 14 15/** 16 * is the same as above. The result attribute contains a string to indicate the content of the file to be read. 17 * encoding is optional and the type is string, indicating the encoding used for the returned data. if not specified, the default is UTF-8.18 */19 reader. readAsText (file [, encoding]); 20 21 22/** 23 * same as above, the result property will contain an ArrayBuffer object to indicate the content of the read file. 24 */25 reader. readAsArrayBuffer (file); 26 27 28/** 29 * is the same as above. The result attribute contains the original binary data of the file to be read. 30 */31 reader. readAsBinaryString (file); since the file base64 is obtained, it is much easier to do things. For example, we can directly post the base64 string to the server. 1 var reader = new FileReader (); 2 3 reader. onload = function (e) {4 var xhr = new XMLHttpRequest (), 5 fromData = new FormData (); 6 7 fromData. append ("base64", e.tar get. result); 8 xhr. open ("post", url, true); 9 xhr. send (fromData); 10} 11 12 reader. readAsDataURL (document. querySelector ("input [type = file]"). files [0]); do you think there is anything wrong? Now that FormData is used, we need to convert the wool into base64! After being converted to base64, the biggest benefit is that the image can be drawn to the Canvas and edited! Crop, graffiti, or something on the client side. After editing, use the toDataURL method of the Canvas object to output the base64 data of the edited image. I will not talk about the implementation of the details here. Let's take a look at what new support the HTML5 file form elements provide: 1 2 Accept attribute, which can be used to restrict the type of files uploaded by users. This property is well supported by IOS and OSX. In addition, the multiple attribute means that you can select multiple files. After this attribute is added, you can use the FormData object to upload data in batches. 1 (function (W, D) {2 var fileForm = document. getElementById ("file_form"), 3 fileImage = document. getElementById ("file_image"); 4 5 function testAjax (files, I) {6 if (I <0) {7 return; 8} 9 10 var xhr = new XMLHttpRequest (), 11 data = new FormData (); 12 13 xhr. onload = function () {14 // recursion 15 testAjax (files, -- I); 16}; 17 data. append ("file_image", files [I]); 18 xhr. open ("post", "test/demo2.php", true); 19 xhr. send (data); 20} 21 22 fileForm. addEventListener ("submit", function (e) {23 e. preventDefault (); 24 var files = fileImage. files; 25 26 testAjax (files, -- files. length); 27}, false); 28 29}) (window, document );

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.