Lightweight Web File Upload component, pure JS,HTML5, HTML4 smart adaptation, support upload progress display (ie10+, standard browser)

Source: Internet
Author: User

Old registered a blog Park account, yesterday only found that even the blog did not open, GitHub is the same, deep feeling ashamed, hurriedly dive a water pressure yajing ' (*∩_∩*)

Anyway Probably many people will use the file upload function, upload the library seemingly also many, for example (jQuery File Uploader, Fineuploader, uploadify, Baidu Web Uploader , etc.), the function is very powerful, The code size is generally larger. At that time, I thought, so a small function, kill chicken with sledgehammer, use library words also have to familiar with its usage, some need to introduce additional library, pure flash not to consider, or to build a wheel, at least after the building can know the underlying principle, the key is to write things, maintenance and modification convenient, The process can be controlled in all directions. Making a wheel is simple, making a good wheel is not so easy. Upload function is completed quickly, but the next time, but found to take over with the need to modify a lot of things, one is the use of the JS Library has changed, and then the UI interface is completely different, then upload the logic and interface to write the dead, encounter different situations need targeted transformation. For a single case, of course, the lightest, only to consider the current situation, not the function can be completely thrown away, can be the most streamlined, but not easy to reuse. If a wheel cannot be reused, it certainly cannot be counted as a qualified wheel. Be aware of this, and now that you have embarked on the road of making wheels, there is no big change in the core functions needed, so let's go. Then fix it all the way, and finally a usable version is completed.

Principle

1. HTML5 upload

This requires browser support, whether it is HTML5 upload or html4 upload, HTML upload control is essential, namely:

<type= "file">
//Listen for the change event of input and get the data to be uploadedInput.onchange =function () {    //Input.files property requires browser support    varFiles = This. Files;  for(vari = 0, len = files.length; i < Len; i++) {        varFile =Files[i]; //File.name | | file.filename = file name        //File.size | | file.filesize = File sizeupload_html5 (file); }};
//HTML5 uploadvarXHR =NewXMLHttpRequest ();//Upload Progress EventXhr.upload.addEventListener ("Progress",function(e) {},false);//upload Complete (success) eventXhr.addeventlistener ("Load",function(e) {//Get Server Response    varText =E.target.responsetext;},false);//Upload Failure EventXhr.addeventlistener ("Error",function(e) {},false);//upload Interrupt (cancel) eventXhr.addeventlistener ("Abort",function(e) {},false);varFD =NewFormData;//add a File object to upload
Fd.append ("File", "file"),Xhr.open ("POST", "Api/upload.ashx"); Xhr.send (FD) ;

2. Html4 upload (Traditional upload)

To implement a no-refresh upload by pointing the target of the form to the name of the IFRAME

<iframename= "Html4-upload-target"></iframe><formAction= "Api/upload.ashx"Method= "POST"enctype= "Multipart/form-data"Target= "Html4-upload-target">    <inputtype= "File"name= "Upfile" /></form>
//IFrame Load Event//Note: The onload event of an IFRAME is supported by a low version of IE, but is invisible (iframe.onload will not be triggered) and needs to be registered by Attacheventfunctionbind_iframe_load (iframe, fn) {if(iframe.attachevent) iframe.attachevent ("onload", FN); ElseIframe.addeventlistener ("Load", FN,false);}//HTML4 Upload Completion callbackBind_iframe_load (IFRAME,function () {    //Get Server Response    varText =Iframe.contentWindow.document.body.innerHTML;});
Beautify

The upload button is ugly, I want to beautify the whole? ie10+ and Standard browser support Input.click () trigger file selection, some people say, the low version of IE can also pop this box ah, here is a pit, the bomb is able to play, but may be based on security considerations can not obtain file data, reported denied access.

Now that you have to click the upload control to select the file, you can use absolute positioning to let the upload control cover the upload button, and then set the transparency of the upload control to 0 to achieve stealth effect, so that the surface click on the Upload button, the actual click is the upload control, the problem will be resolved.

<!--The upload button, the style with its own control, assuming that the width of the height is 120px,36px, relative to the body of the margin is 100px,100px -<aclass= "Upload-target">Select File Upload</a><!--upload the control, select the file (Change event) and append input to the form -<Divstyle= "Width:120px;height:36px;position:absolute;left:100px;top:100px;overflow:hidden;filter:alpha (opacity=0) ; opacity:0; ">    <inputtype= "File"name= "Upfile"style= "width:120px;height:36px;font-size:100px;" /></Div>

About HTML4 upload, just see an iframe without refreshing upload files pit article, interested children shoes can see.

Drag file Upload

File dragging takes advantage of the Drag and drop feature in HTML5, which allows you to drag files from your local computer to a Web page directly.

1. Define the Drop zone

<id= "Drop-area"> Drag the file to this area </div> 

2. Get drag-and-drop data and upload

varBoxdroparea = $ ("#drop-area") [0];//TODO: Detection support Situation//Block Browser from default drag-release to$ (Boxdroparea). On ("DragLeave dragenter drop DragOver",function(e) {e.preventdefault (); E.stoppropagation ();});//get the dragged file object and upload it$ (Boxdroparea). On ("Drop",function(e) {varFiles =E.datatransfer.files; if(!files | | files.length = = 0)return;  for(varFileinchfiles) {        //TODO: Uploading Filesupload (file); }});

For more information about dragging and dropping, refer to this article HTML5 drag & Drop drag and drop introduction

About my upload control

When when, advertising time to ...

Characteristics:
    • Lightweight, not dependent on any JS library, the core code (q.uploader.js) only about 700 lines, min version added up to less than 12KB
    • Pure JS Code, no flash, no need to change the background code to achieve with the progress bar (ie10+, other standard browser) upload, other (eg:ie6+) automatically downgrade to the traditional way to upload
    • The upload core is separated from the UI interface and can be easily customized with the upload interface including the upload button
    • Upload files can also specify the upload parameters, support upload type filtering
    • Complete event callbacks that can be processed separately for each upload process
    • Convenient UI interface, the upload interface can be customized freely

Say there's a truth O (∩_∩) o

Simple invocation example (the exposed global object is Q):

varuploader =Newq.uploader ({URL:"Api/upload.ashx?type=file", Target:document.getElementById ("Upload-target"), View:document.getElementById ("Upload-view"),    //Html5:true,//Whether HTML5 upload is enabled, the default is True    //Multiple:true,//Whether multiple selections are allowed (only HTML5 mode is valid), true by default    //auto:true,//upload immediately after adding a task, true by default        //file types that are allowed or not allowed to be uploaded (allows and disallows can be used single or combined)    //allows: ". txt,.jpg,.png,.gif,.zip,.rar,.7z",    //disallows: ". exe"    //parameters to be sent each time the upload (post mode)Data: {User: "Devin" }});

See the sample code or Github (feel the force of the lattice instantly improved with wood, * ^_^ *)

Https://github.com/devin87/web-uploader

Code download

ASP. NET or other background sample code

node. JS Sample Code

Say in the end

If this article or the project is helpful to you, please do not hesitate to praise. If you have any comments or suggestions, welcome to exchange!

Lightweight Web File Upload component, pure JS,HTML5, HTML4 smart adaptation, support upload progress display (ie10+, standard browser)

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.