HTML5-based preview multi-picture Ajax upload _ajax related

Source: Internet
Author: User
Tags file size file upload jquery library picture hosting

One, about the picture upload what or what
In the era of XHTML, we upload pictures using HTML file controls and upload one at a time. To upload multiple graphs at one time, the practice is to use flash. such as Swfupload.js. Unfortunately, the use of complex points, such as flash files need to be with the page half folder, JavaScript file size is also considerable.

I have previously translated an "Ajax upload upload plug-ins" article, the highlight of this plug-in is the use of hidden IFRAME frames page simulation Ajax upload, but, in fact, or only upload 1 pictures at a time, you can upload more than just.

HTML5 is a good dongdong, one of them is to support multiple image upload, and support Ajax upload, and support upload pictures before the preview, and support the picture drag and drop upload, pure use of the file control implementation, JS code is very few, want to not let people praise all difficult ah!

Second, demo page

If the browser you have on hand is the latest Firefox or Chrome browser, you can click here: Multi-Graph Ajax upload demo based on HTML5

In the demo page, you can click on the file control upload multiple maps, as follows (FireFox 6 screenshot, below):

If there is a non-picture file or picture size is too large, pop-up prompts:

Or you can drag the picture on the desktop directly to the area where you accept the drag:

The image can be previewed directly after it is released (it is not uploaded to the server at this time):

At this point the picture can be deleted in advance, can also be directly uploaded, for example, we click on the upload button, very soon, the image upload success:)!

After uploading the page address is returned, as follows:

At this point, the corresponding upload folder has the following image:

Note: My blog space size is limited, I will regularly clean up the picture folder, so, you do not put here as a free picture hosting site Oh ~ ~

Simple analysis of core skeleton script
First, the file uploaded a core file, is the first two nights slow out of the whole. The filename is: zxxfile.js (you can right-click ...) Download

This file on a few k, hundred line code, mainly responsible for file upload related logic (SELECT, delete, and so on), native JS, therefore, compatible Jquery,yui, Mooyools and so on. Zxxfile.js is actually a small skeleton file, the flesh and so on need to add additional.

Zxxfile.js is actually a small object:

var zxxfile = {
  //skeleton ...

The following table shows the attributes (skeletons) of the Zxxfile object and their corresponding content meanings.

Supplemental Note: The file parameter mentioned above refers to the file object, which has a property value of name, size, type, and so on, and then, in Zxxfile.js, it has a more convenient index property for the element to locate.

Obviously, only the skeleton can do nothing at all. The demo page has the effect, is it according to the above skeleton, according to the actual demand increased flesh and blood. You can directly "right-click-View page source code" at the top of all relevant JavaScript. Or look at my 1.1 points below the mother's story.

We motioned according to the skeleton in the table above. Demo page borrowed the more popular jquery library, skeleton + flesh = plug-ins, of course, the demo page is not running the plug-in to go (although only slightly modified), because the page UI is obviously not enough plug-ins. That is, the use of zxxfile.js skeleton, with the point of your own attributes of the JavaScript library can write your own HTML5 based on the multi-file Ajax upload Plug-ins!

Four, demo page of some code
The overall logic of the demo page code is as follows:

var params = {
  //Flesh and Blood
Zxxfile = $.extend (zxxfile, params);
Zxxfile.init ();

The first is the file control element, as follows:

FileInput: $ ("#fileImage"). Get (0)
because it is a DOM element, the Get method of jquery is applied. The following two parameters are the same.

The file control element in the demo page supports multiple files selection, and its hidden mystery is the red highlighted part of the following code:

<input id= "fileimage" type= "file" size= "" name= "fileselect[" multiple/>

DragDrop and UpButton
drag area and upload button (default hidden):

DragDrop: $ ("#fileDragArea"). Get (0),
UpButton: $ ("#fileSubmit"). Get (0)

Ajax upload Address, there is nothing to say, take the form of the action address:

URL: $ ("#uploadForm"). attr ("action")

Filter method
Filter the selected files. File control what files can be selected, and the demo page is the picture upload related demo, space size is limited, oversized picture or block for good. Obviously, the upload file should be filtered. As a result, the following filter script is available:

Filter:function (files) {
  var arrfiles = [];
  for (var i = 0, file; file = Files[i]; i++) {
    if (file.type.indexOf ("image") = = 0) {
      if (file.size >= 512000) {
        alert (' your "' + + '" picture size is too large, should be less than 500k '); 
      } else {
        Arrfiles.push (file); 
    else {
      alert (' Files ' + + ') is not a picture. '); 
  return arrfiles;

Zxxfile.js automatically consolidates the filtered list of file objects for accurate upload.

Onselect method
file (here is the picture) the method to execute after the selection. In this instance page, the main task of the Onselect method is to preview the local picture in the browser. The core script that is previewed in the browser before the local picture is uploaded is:

var reader = new FileReader (), HtmlImage;
Reader.onload = function (e) {
  htmlimage = '  ';
Reader.readasdataurl (file);

In this demo page, this section completes the script as follows, although it seems some length, in fact, the content is to load some HTML code just:

Onselect:function (Files) {var html = ', i = 0;
  Wait to load an animated GIF $ ("#preview"). html (' <div class= ' upload_loading ' ></div> ');
    var funappendimage = function () {file = Files[i]; if (file) {var reader = new FileReader () Reader.onload = function (e) {html = html + ' <div id= ' UPL  Oadlist_ ' + i + ' "class=" upload_append_list "><p><strong> ' + + ' </strong> ' + ' <a href= "javascript:" class= "Upload_delete" title= "delete" data-index= "' + i + '" > Delete </a><br/> ' + ' <im G id= "Uploadimage_ ' + i +" "src=" ' + + ' "class=" upload_image "/></p> ' + ' <span id=
        "Uploadprogress_ ' + i + '" "class=" upload_progress "></span> ' + ' </div> ';
      Funappendimage ();
    } reader.readasdataurl (file);
      else {//picture-related HTML fragment loaded $ ("#preview"). HTML (HTML); if (HTML) {//Delete method $ (". Upload_delete").Click (function () {Zxxfile.fundeletefile (Files[parseint ($ (this). attr ("Data-index"))]; 
        return false;
      The Submit button displays $ ("#fileSubmit"). Show (); 
      else {//submit button Hidden $ ("#fileSubmit"). Hide ();
Execute picture HTML fragment of the manned Funappendimage ();

Careful you may find that in the above HTML element basically uses the I this index, the function is convenient after the deletion may find the corresponding element.
Then there's one more thing to note: the Zxxfile.fundeletefile () method, which is necessary to actually remove the picture from the file list, and to trigger the callback of the OnDelete method.

OnDelete method
When the picture is uploaded or deleted, execute the Fly method. This example is to fade:

Ondelete:function (file) {
  $ ("#uploadList_" + file.index). fadeout ();

OnDragOver method
This example adds a class name to the method that is executed when the file is dragged over the drag element, as follows:

Ondragover:function () {
  $ (this). addclass ("Upload_drag_hover");

OnDragLeave method
The method that is executed when the file is moved out of the element, this example removes the class name as follows:

Ondragleave:function () {
  $ (this). addclass ("Upload_drag_hover");

OnProgress method
The method that is triggered in the upload. This demo effect is the picture in the upper-left corner with rounded black translucent background elements, the percentage of the increase in the value. Code:

Onprogress:function (file, Loaded, total) {
  var eleprogress = $ ("#uploadProgress_" + file.index), percent = (loaded/ Total *). toFixed (2) + '% '; (). HTML (percent);

Onsuccess method
The method that is executed after the current picture is uploaded successfully. This demo is prompted to return the picture address information:

Onsuccess:function (file, response) {
  $ ("#uploadInf"). Append ("" <p> upload successful, picture address is: "+ response +" "</p>");

OnFailure method
Picture Upload the method of urine out when the belch fart. This demo is a hint, and then the picture is light and transparent:

Onfailure:function (file) {
  $ ("#uploadInf"). Append ("<p> picture" + +) upload failed! </p> "); 
  $ ("#uploadImage_" + file.index). CSS ("opacity", 0.2);

OnComplete method
When all the pictures are uploaded, this instance page puts the value value of the file control blank and the button is hidden:

Oncomplete:function () {
  //submit button hides
  $ ("#fileSubmit"). Hide ();
  The file control value is empty
  $ ("#fileImage"). Val ("");
  $ ("#uploadInf"). Append ("<p> The current picture is all uploaded, you can continue to add upload." </p> ");

PHP Page related code

$FN = (isset ($_server[' http_x_filename ')]? $_server[' Http_x_filename ': false);
if ($FN) {
  file_put_contents ('
    uploads/'. $fn,
    file_get_contents (' php://input ')
  echo "$fn";
  Exit ();

These are the main features or interaction codes. As for the CSS style section and some of the details in the HTML code, I'm too lazy to pick up sesame seeds. You are interested in viewing the source code to observe and observe.

V. Current HTML5 file Ajax upload application range
not only IE browser does not support, the latest win under the Safari browser, or opera does not fully support the HTML5 of the preview of many pictures Ajax upload, then we still have to learn this why? At least now this bird is not.

Indeed, some of our external projects are too early to use this technique for Web pages that are used by a wide range of users. However, for the company intranet project, the application of this absolute OK. I found a very strange problem, many times, the intranet Web page is to support the lower version of IE better, for modern browsers do not support. It's all on the wrong road.

Recently, our company began to change the Intranet project, began based on Chrome and other modern browsers for intranet development (of course, ie can also be used), internal staff to force the use of Chrome browser. As far as our company is concerned, the response is good, both the UI effect, the interaction and the speed experience are good feedback.

Obviously, at least in our company, later to the intranet editor or small secretaries do a multiple map upload function, you can directly use HTML5 file upload, that is, the content of this article. Simplicity, speed, and quickness can make you realize that development is a happy and rewarding thing.

Add that, this article's demo page is used for example, if there are flaws also hope to forgive. Zxxfile.js is also just out of the oven, without experience. We welcome your valuable comments and thank you very much.

Original articles, reproduced please specify from ROK Zhang Xinsen xu-Xin space-Xin Life []
This article address:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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