HTML5-Based Multi-image preview Ajax upload,

Source: Internet
Author: User
Tags image hosting

HTML5-Based Multi-image preview Ajax upload,

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: The size of your blog is limited. I will regularly clean up the image folder. so, please do not use this 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. js 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.

Note: The file parameter mentioned previously refers to the file object. The object's attribute values include name, size, and type. in js, it also has an index attribute that facilitates element locating.

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 = plug-in. Of course, the demo page is not running the plug-in (although you only need to modify it a little ), because the UI of the page is obviously insufficient for plug-ins. That is to say, you can use the zxxFile. js skeleton and click your own JavaScript library to 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's get method is applied. 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. js automatically integrates the list of filtered file objects for accurate upload.

OnSelect Method
File (here is the image) after the selection method. On the instance page, the main task of the onSelect 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 I index is basically used in the above HTML elements, so that the corresponding elements can be found after deletion.
Then, you need to note that the delete event -- The ZXXFILE is executed. funDeleteFile () method, which is required to delete an image from the file list and trigger the onDelete method 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 uploaded, the value of the file control is left blank on the instance page, and the buttons are 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. js has just been released and has never been experienced. 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

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.