HTML5 CSS3 typical case: Drag and Drop upload of images without a plug-in (PreView and batch upload are supported) (2)

Source: Internet
Author: User

Reprinted please indicate the source: http://blog.csdn.net/lmj623565791/article/details/31513065

The previous article has implemented the overall HTML and CSS of this project:

HTML5 CSS3 typical case: Drag and Drop upload of images without a plug-in (PreView and batch upload are supported) (1)

This blog is completed directly on the basis of the previous article. The final result is as follows:

1:


2:

Okay. You can paste the image twice so that you can see the effect ~

We can see that the html of li in our image is still quite complicated, so I made some modifications to the html document:

<span style="font-size:12px;"><body><div id="uploadBox"></div><div id="template" class="hidden">    <li>                <span class="progress"></span>        <span class="percentage"></span>    </li></div></body></span>
As you can see, I wrote li's display to a div # template independently. The default is den. What are the advantages of this operation? Every time we upload a file, there will be a lot of code for creating elements and assigning attributes in js. Generally, the generation of complicated html elements is designed. We recommend that you use this method to simplify the code, it is also conducive to the later maintenance of our code.

Js Code:

<Span style = "font-size: 12px;">/*** User: zhy * Date: 14-6-16 * Time: pm */var ZhangHongyang = ready 5 upload = (function () {var _ ID_UPLOAD_BOX = "uploadBox"; var _ CLASS_PROGRESS = "progress"; var _ CLASS_PERCENTAGE = "percentage "; var _ tip_no_drag = "drag the file to this region to upload it! "; Var _ tip_drag_over =" Release the mouse and upload now! "; Var _ uploadEle = null;/*** initialization object and event * @ private */function _ init () {_ uploadEle = document. getElementById (_ ID_UPLOAD_BOX); _ uploadEle. ondragenter = _ onDragEnter; _ uploadEle. ondragover = _ onDragOver; _ uploadEle. ondragleave = _ onDragLeave; _ uploadEle. ondrop = _ onDrop; _ setStatusNoDrag () ;};/*** dragging status * @ private */function _ setDragOverStatus () {if (_ checkContatinsElements () return; _ uploadEl E. innerText = _ tip_drag_over; _ uploadEle. style. border = "2px dashed #777"; Parameters (_uploadele).css ({lineHeight: $ (_ uploadEle ). height () + "px"});}/*** initialization status * @ private */function _ setStatusNoDrag () {if (_ checkContatinsElements () return; _ uploadEle. innerText = _ tip_no_drag; _ uploadEle. style. border = "2px dashed #777"; Parameters (_uploadele).css ({lineHeight: $ (_ uploadEle ). height () + "px"});}/*** Upload File * @ pri Vate */function _ setDropStatus () {if (_ checkContatinsElements () return; _ uploadEle. innerText = ""; _ uploadEle. style. border = "1px solid #444"; $(_uploadEle).css ({lineHeight: "1em"}); $ (_ uploadEle ). append ("<ul> </ul>") ;};/*** determines whether the file has been uploaded * @ private */function _ checkContatinsElements () {return !! $ (_ UploadEle ). find ("li "). size ();}/*** when ondragenter is triggered * @ private */function _ onDragEnter (ev) {_ setDragOverStatus ();} /*** when ondargmove triggers * @ private */function _ onDragOver (ev) {// The default event behavior must be organized in ondragover. By default, data/elements cannot be placed in other elements. Ev. preventDefault ();}/*** when dragleave triggers * @ private */function _ onDragLeave (ev) {_ setStatusNoDrag ();} /*** ondrop triggers * @ private */function _ onDrop (ev) {// The default behavior of the drop event is opened in the form of a link, so you also need to prevent its default behavior. Ev. preventDefault (); _ setDropStatus (); // get the dragged file var files = ev. dataTransfer. files; var len = files. length; for (var I = 0; I <len; I ++) {// the file to be uploaded is displayed on the page _ showUploadFile (files [I]);} /*** the file to be uploaded is displayed on the page * @ private */function _ showUploadFile (file) {var reader = new FileReader (); // console. log (file) // console. log (reader); // determine the file type if (file. type. match (/image */) {reader. onload = function (e) {v Ar formData = new FormData (); var li = $ ("# template li "). clone (); var img = li. find ("img"); var progress = li. find (". progress "); var percentage = li. find (". percentage "); percentage. text ("0%"); img. attr ("src", e.tar get. result); $ ("ul", $ (_ uploadEle )). append (li); $ (_ uploadEle ). find ("li "). size () = 10 & $ (_ uploadEle ). width ($ (_ uploadEle ). width () + 8) + "px" ).css ("overflow", "auto"); formData. append ("UploadFile", file); // upload the file to the server _ uploadToServer (formData, li, progress, percentage) ;}; reader. readAsDataURL (file);} else {console. log ("this" + file. name + "not an image file! ") ;}}/*** Upload the file to the server * @ private */function _ uploadToServer (formData, li, progress, percentage) {var xhr = new XMLHttpRequest (); xhr. open ("POST", "http: // localhost: 8080/strurts2fileupload/uploadAction", true); xhr. setRequestHeader ('x-Requested-with', 'xmlhttprequest ', 'content-type', 'multipart/form-data;'); // The New HTML5 API, stored information during the upload process xhr. upload. onprogress = function (e) {var percent = 0; if (e. lengthComputable) {// update the page display effect: percent = 100 * e. loaded/e. total; progress. height (percent); percentage. text (percent + "%"); percent> = 100 & li. addClass ("done") ;}}; xhr. send (formData) ;}// publish the init method return {init: _ init }}) (); </span>

Annotations are very detailed. This time, objects are not directly created using the literal, because I do not want users to access all the methods and variables and use simple closures, it can be seen that almost all methods and variables start with _ because I think they are private and I have not published them yet. The only published method is the init Method for users to call. The namespace is also used for the overall method, which is basically the same as the js written by other partners.
HTML FileApi is used in the above js. Here we will introduce it:
1. The File object is the one we used above: File
  1. LastModifiedDate: Thu Dec 26 2013 18:45:08 GMT + 0800 (China Standard Time)
  2. Name: "yt_key.png"
  3. Size: 45524
  4. Type: "image/png"
  5. WebkitRelativePath :""
  6. _ Proto __: File
We can see some of the above attributes. That is to say, if you use a browser that supports html5, set the onchange event for input = type. After you select an image or file, you can view the image or determine the file size and type.
2. FileReader is mainly used to asynchronously Read File Content. Note that it is asynchronous. In the previous example, we used its readAsDataURL method. You can go to Baidu to learn about DataUri. In addition, readAsText is also provided for reading text; readAsArrayBuffer and readAsBinaryString methods; events such as onloadstart, onload, onprogress, onerror, onloaded, and onabort can be viewed one by one.

The call to the last page is as follows:

<span style="font-size:12px;">    <script type="text/javascript" src="jquery-1.8.3.js"></script>    <script type="text/javascript" src="js/html5upload.js"></script>    <script type="text/javascript">        window.onload = function ()        {            ZhangHongyang.html5upload.init();        }        ;    </script></span>




Thank you for your advice ~






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.