HTML5 implementation of image file asynchronous upload

Source: Internet
Author: User

Using the new features of HTML5 file asynchronous upload is easy and convenient, this article mainly shows the JS section. HTML structure. The following code does not use a third-party library, assuming that there is a reference, please note some of the code fragments that are not shown.

Preview of the effect on my side:

1. File not selected 2. File selected

HTML code section:

Idea: In the following code I use the Z-index property of the CSS to hide the input= "file" tag below the id=btnselect element, by triggering a tag click, pop Up the file selection box.

The following masklayer is used to click on the pop-up layer after confirming the button to prevent users from repeatedly clicking confirm button.

    <DivID= "WP"class= "Warpper">                        <aID= "Btnselect">Click to select a photo to upload</a>            <inputID= "UploadFile"type= "File"name= "Myphoto" />                    <ButtonID= "Btnconfirm"class= "BTN" >Confirm Upload</Button>            </Div>    <DivID= "Masklayer"class= "Mask-layer"style= "Display:none;">        <P>The picture is being uploaded ...</P>    </Div>

JS picture file Verification Section:

The validation section is: size. Whether it has been selected, the type of file is three parts. The first CreateObject method is to create a preview path to the local picture file. Verify that it is empty, file type, and file size, and return if the condition is not met

False to generate a picture preview in the DOM after the above 3 conditions are met. Add the IMG element and use the Createobjecturl () method to get the preview path.

Code:

    //gets the URL address of the data    functionCreateobjecturl (BLOB) {if(window. URL) {returnwindow.        Url.createobjecturl (BLOB); } Else if(window.webkiturl) {returnWindow.webkitURL.createObjectURL (BLOB); } Else {            return NULL; }    }        //File Detection    functioncheckfile () {//Get File        varFile = $$ ("UploadFile"). Files[0]; //file is null inferred        if(File = =NULL|| File = = =undefined) {Alert ("Please select the file you want to upload!" "); $$("Btnselect"). InnerHTML = "Click to select photos to upload"; return false; }                //test File Type        if(File.type.indexOf (' image ') = = =-1) {alert ("Please select a picture File!"

"); return false; } //Calculate File Size varSize = Math.floor (file.size/1024);if(Size > 5000) {alert ("Upload files must not exceed 5m!"); return false; }; //Add preview Image$$ ("Btnselect"). InnerHTML = "; };

JS Ajax Request Section:

Description: The first listener file selects a change event, and a preview is run after the validation criteria are met. The second event listens for a response that pops up the form when a listener clicks Btnselect. The following is an event listener confirming the upload button, which starts sending an AJAX request. The CREATEXHR () method here creates the XMLHttpRequest object. The code I did not post, including the AddEventListener () method, these 2 parts can refer to other articles.

    //Monitor Picture URL address ChangeAddEventListener ($$ ("UploadFile"), "change",function() {checkfile ();        }); //Listen Click file Select buttonAddEventListener ($$ ("Btnselect"), "click",function() {        //Pop-up file selection box$$ ("UploadFile"). Click ();    }); //Listen for click events to confirm the upload buttonAddEventListener ($$ ("btnconfirm"), "click",function(e) {if(Checkfile ()) {Try {                //Run the upload operationvarXHR =createxhr (); $$("Masklayer"). Style.display = "Block"; Xhr.open ("Post", "/uploadphoto.action",true); Xhr.setrequestheader ("X-requested-with", "XMLHttpRequest"); Xhr.onreadystatechange=function() {                    if(Xhr.readystate = = 4) {                        varFlag =Xhr.responsetext; if(flag = = "Success") {alert ("The picture was uploaded successfully. "); } Else{alert ("Image upload successful!" ");                                                }; $$("Masklayer"). Style.display = "None";                };                }; //form Data                varFD =NewFormData (); Fd.append ("Myphoto", $$ ("UploadFile"). Files[0]); //Run SendXhr.send (FD); } Catch(e) {console.log (e);        }        }        }); 

?

The above is all the main code sections. Suppose you have any questions to contact me. Welcome to the Exchange.

?

HTML5 to implement an asynchronous upload of a picture file

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.