Lightweight Web File Upload component, support HTML5, support upload progress display (ie10+, standard browser), file drag and drop, downgrade support ie6+

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:


 
<input type="file">
/ / Listen to the change event of input to get the data to be uploaded
Input.onchange = function () {
     //input.files property requires browser support
     Var files = this.files;

     For (var i = 0, len = files.length; i < len; i++) {
         Var file = files[i];

         //file.name || file.fileName => file name
         //file.size || file.fileSize => file size

         Upload_html5(file);
     }
};
//html5 upload
Var xhr = new XMLHttpRequest();

/ / Upload progress event
xhr.upload.addEventListener("progress", function (e) { }, false);
/ / Upload completed (successful) event
xhr.addEventListener("load", function (e) {
     / / Get the server response
     Var text = e.target.responseText;
}, false);
/ / Upload failure event
xhr.addEventListener("error", function (e) { }, false);
/ / Upload interrupt (cancel) event
xhr.addEventListener("abort", function (e) { }, false);

Var fd = new FormData;
/ / Add the file object to be uploaded
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


<iframe name="html4-upload-target"></iframe>
<form action="api/upload.ashx" method="post" enctype="multipart/form-data" target="html4-upload-target">
     <input type="file" name="upfile" />
</form>
//iframe load event
//Note: The lower version ie supports the onload event of the iframe, but it is invisible (the iframe.onload mode will not be triggered), you need to register with attachEvent
Function bind_iframe_load(iframe, fn) {
     If (iframe.attachEvent) iframe.attachEvent("onload", fn);
     Else iframe.addEventListener("load", fn, false);
}

//html4 upload complete callback
Bind_iframe_load(iframe, function () {
     / / Get the server response
     Var text = 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.


<!-- Upload button, the style is controlled by yourself, assuming that the width and height are 120px and 36px respectively, and the margin relative to the body is 100px, 100px -->
<a class="upload-target">Select file upload</a>

<!-- Upload control, after selecting the file (change event) append input to form -->
<div style="width:120px;height:36px;position:absolute;left:100px;top:100px;overflow:hidden;filter: alpha(opacity=0);opacity:0;">
     <input type="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.


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):


Var uploader = new Q.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, //allow multiple choices (only html5 mode is valid), the default is true
     //auto: true, //Is it uploaded immediately after adding a task, the default is true
    
     //File types that are allowed or not allowed to be uploaded (allows and disallows can be used singly or in combination)
     //allows: ".txt,.jpg,.png,.gif,.zip,.rar,.7z",
     //disallows:".exe"

     / / Each time the upload will be sent parameters (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, support HTML5, support upload progress display (ie10+, standard browser), file drag and drop, downgrade support ie6+


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.