HTML5-Based Multi-image preview Ajax upload,

Source: Internet
Author: User
Tags image hosting

HTML5-Based Multi-image preview Ajax upload,

From http://www.zhangxinxu.com by zhangxinxu
Address: http://www.zhangxinxu.com/wordpress? P = 1923

I. What to upload images?

In the era of XHTML, only one image can be uploaded at a time using the HTML file control. To upload multiple images at a time, flash is used. For example, swfupload. js. Unfortunately, the use of complex points, such as flash files need to be the same as the page parent folder, JavaScript file size is also very large.

I have translated and edited an article titled "Ajax Upload Multifile Upload plug-in". The highlight of this plug-in is that the hidden iframe framework page is used to simulate ajax Upload. However, in fact, you can upload only one image at a time.

HTML5 is a good stuff, one of which supports multi-Image Upload and ajax upload. It also supports preview of images before upload, and supports drag-and-drop upload of images, which is purely implemented using the file control, it's hard to get a compliment on JS Code!

Ii. demo page

If your browser is the latest FireFox or Chrome browser, you can click here: HTML5-Based Multi-image Ajax upload demo

On the demo page, you can click the file control to upload multiple images, as shown in the following figure (for example, FireFox 6, the same below ):

If there are non-image files or the image size is too large, a prompt is displayed:

Alternatively, you can drag the image on the desktop to the area where the image is dragged:

After the image is released, you can preview it directly (it has not been uploaded to the server yet ):

At this time, the image can be deleted in advance or uploaded directly. For example, we click the upload button. Soon, the image has been uploaded successfully :)!

The address of the uploaded page is returned as follows:

In this case, the image below the corresponding upload folder will be available:

Note:My blog has limited space. I will regularly clean up the image folder. so, please do not use it as a free image hosting place ~~

Iii. Simple Analysis of core skeleton scripts

First, a core File Uploaded By the file is swallowed up in the first two nights. File Name: zxxFile. js (right-click ...... Download)

This file has several K lines of code and is mainly responsible for file upload-related logic (such as selection and deletion) and native JS. Therefore, it is compatible with jQuery, YUI, and MooYools.zxxFile.jsIt is actually a small skeleton file, and the physical body needs to be added separately.

ZxxFile. js is actually a small object:

Var ZXXFILE = {// skeleton ...}

The following table shows the attributes (skeleton) of the ZXXFILE object and their meanings.

Attribute or Method Default method or value Meaning
FileInput Null DOM element. Table file control elements.
DragDrop Null DOM element. Drag-and-drop sensor area elements in the table.
UpButton Null DOM element. The button element to submit.
Url "" String. Indicates the URL for file ajax upload.
FileFilter [] The filtered array of file objects, which is generally not involved in initialization. Can be used to determine the number of the current list.
Filter Function (files ){
Program program return files;
}
Function. Used to filter the list of selected files. For example, you can only select an image or a size limit. Supports one parameter (files), which is an array of file objects and must return an array.
OnSelect Function (){} Function. Callback executed when the local file is selected. Supports a file array.
OnDelete Function (){} Function. This method is used when an uploaded file is uploaded successfully (automatically) or deleted (manually. A file is accepted, and the table is currently deleted.
OnDragOver Function (){} Function. This method is used when a local file is dragged to a drag-and-drop sensitive element. This indicates the sensitive element in the method, that is, the dragDrop element above.
OnDragLeave Function (){} Function. This method is executed when the local file leaves the drag and drop sensitive elements. This indicates the sensitive element in the method, that is, the dragDrop element above.
OnProgress Function (){} Function. The callback method executed during file upload. Three parameters (file, loaded, and total) are accepted, indicating the object of the currently uploaded file, the number of uploaded bytes, and the total number of bytes of the file.
OnSuccess Function (){} Function. Callback Method for successful file upload. Two parameters (file, response) are accepted, indicating the object that is successfully uploaded and the character content returned by the background.
OnFailure Function (){} Function. Callback Method for failed file upload. Two parameters (file, response) are accepted, indicating the file object that failed to be uploaded and the character content returned by the background.
OnComplete Function (){} Function. The callback method for the current Object List to be uploaded and executed. No available parameters.
FunDragHover Omitted Method. File drag. Non-available API.
FunGetFiles Omitted Method. Obtain the selected or drag-and-drop file. Non-available API.
FunDealFiles Omitted Method. Process the selected file. Non-available API.
FunDeleteFile Omitted Method. Delete an object from the list. This method must be called when a file is manually deleted.
FunUploadFile Omitted Method. File Upload. Non-available API.
Init Omitted Method. Initialization is mainly the event binding of an element. Non-available API.

Note:The file parameter mentioned previously refersfile objectObject. The property value of this object hasname, size, typeAnd thenzxxFile.jsIt also has a convenient element to locateindexIndex properties.

Obviously, only the skeleton can basically do nothing. The reason why the demo page is effective is that it adds flesh and blood based on the above skeleton and actual needs. You can right-click to view the source code of the page to view all related JavaScript. Or let's see what I told you.

Follow the skeleton in the above table. The demo page borrowed the popular jQuery library,Skeleton + flesh = pluginOf course, the demo page is not running on the plug-in (although only a slight modification is required), because the UI of the page is obviously insufficient for plug-ins. That is to say, usingzxxFile.jsSkeleton. With your own JavaScript library, you can write your own HTML5-Based Multi-file Ajax upload plug-in!

4. demo Page code

The overall logic of the demo Page code is as follows:

Var params = {// flesh and blood}; ZXXFILE = $. extend (ZXXFILE, params); ZXXFILE. init ();

FileInput
The first is the file control element, as follows:

fileInput: $("#fileImage").get(0)

Because it is a DOM element, jQuery'sgetMethod. The following two parameters are the same.

The file control element on the demo page supports multi-file selection. Its hidden xuanjicang is highlighted in red in the following code:

<input id="fileImage" type="file" size="30" name="fileselect[]" multiple />

DragDrop and upButton
Drag the area and upload button (hidden by default ):

dragDrop: $("#fileDragArea").get(0),upButton: $("#fileSubmit").get(0)

Url
There is nothing to say about the Ajax upload address. The form's action address is used:

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

Filter Method
Filter the selected files. The file control can be used to select any file, while the demo page is a demo related to Image Upload. The space is limited, so it is better to block ultra-large images. Obviously, you need to filter uploaded files. Therefore, the following filtering 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 ('yours "'+ file. name + '"the image size is too large and should be smaller than 500k');} else {arrFiles. push (file) ;}} else {alert ('file "'+ file. name + '"is not an image. ') ;}} Return arrFiles ;}

zxxFile.jsThe filtered file object list is automatically integrated for accurate upload.

OnSelect Method
File (here is the image) after the selection method. On the instance page,onSelectThe main task of this method is to preview the local image in the browser. The core script to preview the local image in the browser before it is uploaded is:

var reader = new FileReader(), htmlImage;reader.onload = function(e) {    htmlImage = '';}reader.readAsDataURL(file);

On this demo page, the complete script is as follows. Although it seems to have some length, the content is actually loading some HTML code:

OnSelect: function (files) {var html = '', I = 0; // wait for loading GIF animation $ ("# 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 = "uploadList _' + I + '" class = "upload_append_list"> <p> <strong>' + file. name + '</strong>' + '<a href = "javascript: "class =" upload_delete "title =" delete "data-index =" '+ I +' "> Delete </a> <br/> '+'  </p>' + '<span id =" uploadProgress _' + I + '"class =" upload_progress "> </span> '+' </div> '; I ++; funAppendImage ();} reader. readAsDataURL (file);} else {// loading image-related HTML fragments $ ("# preview" ).html (html); if (html) {// deletion method $ (". upload_delete "). click (function () {ZXXFILE. funDeleteFile (files [parseInt ($ (this ). attr ("data-index")]); return false ;}); // The submit button is displayed $ ("# fileSubmit "). show ();} else {// The submit button hides $ ("# fileSubmit "). hide () ;}}; // executes the manned funAppendImage () of the HTML part of the image ();}

You may find that the above HTML elements are basically used.iThis index is used to facilitate subsequent deletion of corresponding elements.
Then, you need to note that the deletion event is executed.ZXXFILE.funDeleteFile()Method, which is required to delete the image from the file list and triggeronDeleteMethod callback.

OnDelete Method
Execute the flying method when the image is uploaded or deleted. This instance is used to fade away:

onDelete: function(file) {    $("#uploadList_" + file.index).fadeOut();}

OnDragOver Method
This example adds a class name, as shown in the following code:

onDragOver: function() {    $(this).addClass("upload_drag_hover");}

OnDragLeave Method
The method executed when the file is removed from the element. This instance removes the class name, as shown below:

onDragLeave: function() {    $(this).addClass("upload_drag_hover");}

OnProgress Method
Method triggered during upload. In this demo, there is a black translucent background element with a rounded corner in the upper left corner of the image, and the percentage value is increasing. Code:

onProgress: function(file, loaded, total) {    var eleProgress = $("#uploadProgress_" + file.index), percent = (loaded / total * 100).toFixed(2) + '%';    eleProgress.show().html(percent);}

OnSuccess Method
The method to run after the current image is uploaded successfully. This demo displays the image address information returned:

OnSuccess: function (file, response) {$ ("# uploadInf "). append ("" <p> uploaded successfully. The image address is "+ response +" "</p> ");}

OnFailure Method
How to urinate an image when it is uploaded. This demo is a prompt, and the image is light and transparent:

OnFailure: function (file) {$ ("# uploadInf"). append ("<p> image" + file. name + "Upload Failed! </P> "); $ (" # uploadImage _ "+ file.index.html .css (" opacity ", 0.2 );}

OnComplete Method
After all the images are uploadedvalueIf the value is left blank, the button is hidden:

OnComplete: function () {// The submit button hides $ ("# fileSubmit "). hide (); // set the value of the file control to null $ ("# fileImage "). val (""); $ ("# uploadInf "). append ("<p> the current image has been uploaded. You can add another image. </P> ");}

PHP page 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 "http://www.zhangxinxu.com/study/201109/uploads/$fn";    exit();}

These are the main functions or interactive code. As for the CSS style section and some details in HTML code, I am too lazy to pick up sesame seeds. If you are interested, you can view the source code.

5. Application Scope for uploading HTML5 files via Ajax

Not only does the IE browser not support this, but the Safari browser in the latest win, or Opera does not fully support HTML5 multi-image preview Ajax uploads. Why should we learn this? At least the bird does not exist now.

Indeed, it is too early for some of our external projects to use this technology for web pages used by users. However, for the company's Intranet project, the application is absolutely OK. I found a very strange problem. In many cases, the Intranet web pages support low-version IE better, but not modern browsers. This is completely on the wrong path.

Recently, our company began to change its internal network project and began to develop internal networks based on modern browsers such as Chrome (of course, ie can also be used). Internal staff force Chrome. As far as our company is concerned, the response is very good, whether it is the UI effect, interaction or speed experience feedback is good.

Obviously, at least in our company, you can directly upload HTML5 files by providing the multi-graph upload function for intranet editors or small secretaries in the future, that is, the content mentioned in this article. Simple, fast, and quick, it will make you realize that development is a happy and valuable thing.

In addition, the demo page in this article is used for examples. If any of the examples is missing, please forgive me.zxxFile.jsIt was just released, without experience. Thank you for your comments.

Original article, reproduced please indicate from Zhang xinxu-xin space-xin Sheng live [http://www.zhangxinxu.com]
Address: http://www.zhangxinxu.com/wordpress? P = 1923

(This article is complete)

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.