Asynchronous upload of image files using HTML5

Source: Internet
Author: User

Using the new HTML5 features for asynchronous file upload is very simple and convenient. This article mainly shows the JS section and the html structure. The following code does not use the third release library. If you have any reference, pay attention to some undisplayed code snippets. Effect preview on my side:

1. File not selected 2. File selected

HTML code:

Idea: In the following code, I used the z-index attribute of css to hide the input = "file" tag under the id = btnSelect element. After a tag is clicked, the file selection box is displayed. The following masklayer is used to click the pop-up layer after the confirmation button, so that you do not need to click the confirmation button again.

Click to select the photo to upload                    Confirm upload                        

Uploading image...

JS image file Verification Section:

The verification part is size, whether it has been selected, and the file type. The first createObject method is to create the preview path of the local image file, and verify whether it is null, the file type, and the file size in turn. If the conditions are not met, the system will return

False. After the preceding three conditions are met, the image preview is generated in the dom, the img element is added, and the preview path is obtained using the createObjectURL () method.

Code:

// Obtain the Data URL function createObjectURL (blob) {if (window. URL) {return window. URL. createObjectURL (blob);} else if (window. webkitURL) {return window. webkitURL. createObjectURL (blob);} else {return null ;}// file detection function checkFile () {// get the file var file =$ ("uploadFile "). files [0]; // if (file = null | file = undefined) {alert ("select the file you want to upload! "); $ (" BtnSelect "). innerHTML = "click to select the photo to upload"; return false;} // detect the file type if (file. type. indexOf ('image') ===- 1) {alert ("select an image file! "); Return false;} // calculate the file size var size = Math. floor (file. size/1024); if (size> 5000) {alert ("the size of the uploaded file cannot exceed 5 MB! "); Return false ;}; // Add preview image $ (" btnSelect "). innerHTML = "";};

JS Ajax request section:

Note: The first listening file selects the change event. After the verification conditions are met, the event is previewed. The second listening event is the response in the pop-up window when the listener clicks btnSelect, the following is an event listener that confirms the upload button and starts to send Ajax requests. The createXHR () method here is used to create the XMLHttpRequest object. I have not posted the Code, including the addEventListener () method. For more information about the two parts, see other articles.

// Listen to the image URL to change addEventListener ($ ("uploadFile"), "change", function () {checkFile ();}); // listener click the file selection button addEventListener ($ ("btnSelect"), "click", function () {// The file selection box is displayed $ ("uploadFile "). click () ;}); // listen to the upload confirmation button click event addEventListener ($ ("btnConfirm"), "click", function (e) {if (checkFile () {try {// execute the upload operation var xhr = createXHR (); $ ("maskLayer "). style. display = "block"; xhr. open ("post", "/uploadPhoto. ac Tion ", true); xhr. setRequestHeader ("X-Requested-With", "XMLHttpRequest"); xhr. onreadystatechange = function () {if (xhr. readyState = 4) {var flag = xhr. responseText; if (flag = "success") {alert ("image uploaded successfully! ");} Else {alert (" image uploaded successfully! ") ;};$ $ (" MaskLayer "). style. display = "none" ;};}; // form data var fd = new FormData (); fd. append ("myPhoto", $ ("uploadFile "). files [0]); // execute xhr. send (fd);} catch (e) {console. log (e );}}});

The above is all the main code. If you have any questions, please contact me.

Author: Ziv Serena
Source: http://imziv.com/
About the author: programmers who focus on Java Technology keep a high interest in JS development. Like music, reading, FM, etc.
The copyright of this article is shared by the author and the blog. You are welcome to repost this article, but you must keep this statement without the author's consent and provide a connection to the original article on the article page.
If there is a problem, you can mail: wewoor@foxmail.com
Weibo: Ziv Xiaowei

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.