Multi-file upload based on jquery

Source: Internet
Author: User

1. File Upload foreground design

Speaking of the front desk design, but also really some do not know how to say good, or the old way, directly to the direct, in this also explained: I am not good at doing PS, so a lot of material (Pictures) are online search, this upload program can upload various documents, as to Which? I don't count, I don't mind you counting, I'll just use a simple picture to come up with a demo, with a preview feature.

There is no time to upload the interface (a bit ugly, MO dislike)

To start uploading:

This time when the mouse moves up, you can work on the file (delete the selected photos and view the file name)


Upload the picture (because I am using JS simulation upload, so the total progress bar above will not move, complete program completely no problem):

2. Code explanation

Front interface, I am still very simple, just a div,div with an ID, as follows:

<div id= "Imgupload" ></div>

There is only one jquery required for plugins

<script type= "Text/javascript" src= "Js/jquery-2.2.1.min.js" ></script>

How do you do it? I'm all wrapped up, just the following simple code:

$ ("#imgUpload"). Initupload ({        "url": "Servlet/progressuploadservlet",        "Selectbttext": "Select Picture",       //" FileType ":" image/* ",        " size ":" Ten "    });

Description: It is also the main function of the program performance bar

initupload Parameter Object description: parameter        must      default                                                                function url           optional        default "Servlet/progressuploadservlet"                              Upload background service interface  Selectbttext Optional file        Select File                                                         upload button information fileType optional        (all files) Reference: http://www.cnblogs.com /joans/p/3158582.html        setting File upload format size optional           non-        qualified                                                             file (single) size, in megabytes

As for the CSS does not seem to be good to say, if interested can download the source code, everything has, hehe

As for JS, the important explanation:

First understand the following to select multiple files: Also very simple, with HTML tags can be implemented

<input type= "file" id= "input"  
Of course, I click on the button, a little bit know how to realize, nothing is to use JS to create a inpit simulation click.
/** *  ZXM * Function: Click the button can pop up a dialog box, select File * @param uploadid upload the file ID */function selectfile (uploadid) {    var inputobj= Document.createelement (' input ');    Inputobj.setattribute (' id ', uploadid+ ' _file ');    Inputobj.setattribute (' type ', ' file ');    Inputobj.setattribute ("Style", ' Visibility:hidden ');    Inputobj.setattribute ("Multiple", "multiple");    Inputobj.setattribute ("onchange", "Showfile (This.files, '" "+uploadid+") ");//This sentence is very important, the file selection will trigger this event    var opt=$ (" # "+uploadid"). Data ("opt");    if (opt.filetype) {        Inputobj.setattribute ("accept", Opt.filetype);    }    Document.body.appendChild (inputobj);    Inputobj.click ();    $ ("#" +opt.uploadid). Removedata ("Filearray");    var filearray = new Array ();    $ ("#" +opt.uploadid). Data ("Filearray", Filearray);}
Choose the file after what to do, of course, is displayed: if it is a picture of the preview, if it is a file in other formats to select the corresponding picture displayed, the code is as follows:

/** * ZXM * Function: Display thumbnail * @param files file list * @param Uploadid file submitted function ID, which is the initialized ID */function showfile (files,uploadid) {VA  R imgtest=/image\/(\w) */; Verify the picture format var audiotest =/audio\/(\w) */; Verify music var videotest =/video\/(\w) */; Video verification var pdftest =/application\/pdf/; PDF verification var ziptest =/application\/(zip|rar|7z|cab|iso)/;    Compression validation var opt=$ ("#" +uploadid). Data ("opt"); if (window.        FileReader) {$ ("#" +uploadid+ "_context"). HTML ("");           for (var i =0; i<files.length;i++) {var file = Files[i];                     if (opt.size!= "") {if (file.size> (opt.size) *1048576) {alert ("file" +file.name+ ", too large to provide upload");                Continue            }} var reader = new FileReader ();            Reader.readasdataurl (file);                Reader.onload = (function (f,i,uploadid) {var filearray=$ ("#" +uploadid). Data ("Filearray");                Filearray[filearray.length]=i; $ ("#" +uploadid). Data ("Filearray", Filearray);                    return function (e) {var result = E.target.result;                    var appendData = "";  if (Imgtest.test (File.type)) {appendData + = "<div class= ' showitemdiv ' id= '" +  Uploadid + "_showitemdiv_" + i + "' style= ' background-image:url (" + result + "); ' Onmouseover=showitemtitlestatus ('" + I                    + "', ' true ', '" + Uploadid + "') onmouseout=showitemtitlestatus ('" + i + "', ' false ', '" + Uploadid + "') >"; }else if (audiotest.test (File.type)) {appendData + = "<div class= ' showitemdiv ' id= '" + UPL Oadid + "_showitemdiv_" + i + "' style= ' Background-image:url (images/filetype/muisic.png); background-repeat:no-repeat; ' Onmouseover=showitemtitlestatus (' + i + ' ', ' true ', ' + Uploadid + ') onmouseout=showitemtitlestatus (' "+ i +" ', ' false ',                    "+ Uploadid +" ') > ";               }else if (videotest.test (File.type)) {         AppendData + = "<div class= ' showitemdiv ' id= '" + Uploadid + "_showitemdiv_" + i + "' style= ' background-image:u RL (images/filetype/avi.png); background-repeat:no-repeat; ' Onmouseover=showitemtitlestatus (' "+ i +" ', ' true ', ' "+                    Uploadid + "') onmouseout=showitemtitlestatus ('" + i + "', ' false ', '" + Uploadid + "') >"; }else if (pdftest.test (File.type)) {appendData + = "<div class= ' showitemdiv ' id= '" + Uploadid + "_ Showitemdiv_ "+ i +" ' style= ' Background-image:url (images/filetype/pdf.png); background-repeat:no-repeat; ' Onmouseover=showitemtitlestatus (' + i + ' ', ' true ', ' + Uploadid + ') onmouseout=showitemtitlestatus (' "+ i +" ', ' false ',                    "+ Uploadid +" ') > "; }else if (ziptest.test (File.type)) {appendData + = "<div class= ' showitemdiv ' id= '" + Uploadid + "_ Showitemdiv_ "+ i +" ' style= ' Background-image:url (images/filetype/zip.png); background-repeat:no-repeat; ' Onmouseover=showitemtitleStatus (' + i + ' ', ' true ', ' + Uploadid + ') onmouseout=showitemtitlestatus (' "+ i +" ', ' false ', ' "+ Uploadid +" ') > "; }else{AppendData + = "<div class= ' showitemdiv ' id= '" + Uploadid + "_showitem Div_ "+ i +" ' style= ' Background-image:url (images/filetype/file.png); background-repeat:no-repeat; ' Onmouseover= Showitemtitlestatus (' + i + ' ', ' true ', ' + Uploadid + ') onmouseout=showitemtitlestatus (' "+ i +" ', ' false ', ' "+ Uploadi                    D + "') >"; }//Below is about the Delete and confirm button AppendData + = "<div class= ' showitemstatus ' id= '" +uploadid+ "_showi                    Temstatus_ "+i+" > "; AppendData + = " ";                    AppendData + = "</div>"; The following is about the file name AppendData + = "<div class= ' filenamediv ' id= '" +uploadid+ "_showitem_file_name_" +i+ "' >" + F.name + "</div>"; This is a progress bar appenddata+= "<div class= ' prograssbar ' ><div class= ' prograssbar_inner ' id= '" +uploadid                    + "_showitem_prograssbar_" +i+ "></div></div>";                    AppendData + = "</div>";                $ ("#" + Uploadid + "_context"). Append (AppendData);        }}) (File,i,uploadid);        } var contentdiv= "<div class= ' uploadbtdiv ' >";        contentdiv+= "<div class= ' Prograssbarsummer ' >";        contentdiv+= "<div class= ' prograssbar_inner prograssbarsummer_inner ' ></div>";        contentdiv+= "<div class= ' Prograssbar_number ' ></div>";        contentdiv+= "</div>";        contentdiv+= "<div class= ' prograssbarsummer_message ' >"; contentdiv+= "<span class= ' prograssbar_size ' ></span><span class= ' prograssbar_usetime ' ></span ><span class= ' prograssbar_needtime ' ></span><span class= ' PROGRASSBAr_velocity ' ></span> "contentdiv+=" </div> ";        contentdiv+= "<div>"; contentdiv+= "<button class= ' UPLOADBT ' id= '" +uploadid+ "_UPLOADBT ' Onclick=uploadfile ('" +uploadId+ "') > Upload </        Button> "; contentdiv+= "<button id= '" +uploadid+ "_CANCELDBT ' class= ' CANCELBT ' Onclick=cancelfile ('" +uploadId+ "') > Cancel <        /button> "; contentdiv+= "<button id= '" +uploadid+ "_cleanbt ' class= ' cleanbt ' Onclick=cleanfile ('" +uploadid+ "') > Empty </        Button> ";        contentdiv+= "</div>";        contentdiv+= "</div>";    $ ("#" +uploadid+ "_context"). Append (Contentdiv);    }else{alert ("Your browser does not support thumbnail display"); }}

Here's a slightly interesting thing to FileReader, and I'll explain it a little bit:

It's very simple, just a "read file", a little more professional is: The FileReader object lets the Web application's asynchronous read file content (or raw data buffer) stored on the user's computer, using a file or Blob object to specify the file or data to read.

There are five ways to read FileReader:

    1. abort()  终端读取
    2. readAsBinaryString() 返回文件内容的二进制格式(不推荐使用)
    3. readAsArrayBuffer()  返回文件内容的 ArrayBuffer 格式(图片文件推荐使用)
    4. readAsDataURL()Returns the data URL format of the file contents
    5. readAsText()Returns the plain text format of the contents of a file

At the same time this filereader also carries some events, these times are also simple, in order to facilitate understanding, I also wrote a small test file, see below:

<! DOCTYPE html>
var formData = new FormData ();
It's not really a mystery, is it? When an HTML <form> element specifies a form, the object is filled with the form of a key/value. It also encodes the file into the content.Note: It also encodes the file to enter the content

If you want to know more, check out this link: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

So I can use this thing and put in some files I want to upload.

As for uploading, I would naturally choose jquery to upload and look at the following code:

$.ajax ({        type: "Post",        Url:url,        data:formdata,        processdata:false,        contenttype:false,        Success:function (data) {            //alert (data)        },        error:function (e) {            //alert ("File upload Failed");}    )
Note that there are two very important properties
Processdata:false,

Contenttype:false,
These two must be written, as to what use, look up the jquery document will know

OK, the main thing is this point, the other is the data acquisition, as well as the effect of the display problem, if interested can see the source code, if there is any good ideas or suggestions, can also communicate with me

Front desk JS test source code address: Http://pan.baidu.com/s/1eRGPoUe

Background program complete code (Java): Http://pan.baidu.com/s/1kVAjGaV







Multi-file upload based on jquery

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.