Home Web Front-end JS Tutorial How to create preview image effect with HTML5+ajax

How to create preview image effect with HTML5+ajax

Apr 04, 2018 pm 01:40 PM
h5 picture

This time I will show you how to use HTML5+ajax to create a preview image effect. What are the precautions for HTML5+ajax to create a preview image effect? ​​ The following is a practical case, let’s take a look.

1. About image uploading
In the era of XHTML, we can only upload one image at a time using the HTML file control. To upload multiple images at once, the method is to use flash. For example swfupload.js. Unfortunately, there are some complications in using it, such as the flash file needs to be in the same parent folder as the page, and the JavaScript file size is also considerable.

I have previously translated and edited an article on "Ajax Upload Multi-File Upload Plug-in". The highlight of this plug-in is to use a hidden iframe frame page to simulate ajax upload. However, in fact , you can still only upload 1 picture at a time, you can upload it multiple times.

HTML5 is a good thing. One of them is that it supports multiple image uploads, supports ajax upload, supports preview of images before uploading, and supports drag and drop upload of images. It is purely implemented using the file control and has very few JS codes. , it’s hard not to be praised!

2. Demo page

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

In the demo page, you can click the file control to upload multiple images, as shown below (FireFox 6 screenshot, the same below):

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

Or you can directly drag the image on the desktop to the area that accepts dragging:

After releasing, the image can be previewed directly (it has not been uploaded to the server yet):

This Pictures can be deleted in advance or uploaded directly. For example, we click the upload button and soon, the picture is uploaded successfully :)!

The page address after uploading is returned, as follows:

At this time, the corresponding upload folder is below Here is this picture:

Note: The space on my blog is limited, and I will clean up the picture folder regularly. So, please do not regard this as a free picture hosting. Occasion~~

3. Simple analysis of the core skeleton scriptThe first is a core file for file upload, which was slowly compiled in the previous two nights. The file name is: zxxFile.js (you can right-click... to download)

This file is only a few kilobytes and has about a hundred lines of code. It is mainly responsible for the logic related to file upload (selection, deletion, etc.), native JS, so , compatible with jQuery, YUI, MooYools, etc. zxxFile.js is actually a small skeleton file, and the body needs to be added separately.

zxxFile.js is actually just a small object:

var ZXXFILE = {
  //骨架们...
}
Copy after login

The following table shows the attributes (skeleton) of the ZXXFILE object and its corresponding content and meaning.

Additional explanation: The file parameter mentioned many times above refers to the file object object. The attribute values ​​​​of this object include name, size, type, etc. Then, in zxxFile In .js, it also has an index attribute that facilitates element positioning.

Obviously, only the skeleton can basically do nothing. The reason why the demo page is effective is that it follows the above skeleton and adds flesh and blood according to actual needs. You can directly "right-click - view page source code" to view all related JavaScript. Or read my mother-in-law’s story below.

我们按照上面表格中的骨架进行示意。demo页面借用了比较流行的jQuery库,骨架+血肉 = 插件,当然,demo页面并不是奔着插件去的(虽然只需稍加修改),因为页面的UI显然不够插件的份。也就是说,利用zxxFile.js骨架,配合点你自己属性的JavaScript库就可以书写属于你自己的基于HTML5的多文件Ajax上传插件啦!

四、demo页面的些代码demo页面代码整体逻辑如下:

var params = {
  //血肉们
};
ZXXFILE = $.extend(ZXXFILE, params);
ZXXFILE.init();
Copy after login

fileInput首先是file控件元素,如下:

fileInput: $("#fileImage").get(0)因为是DOM元素,所以应用了jQuery的get方法。下面两个参数同。

demo页面中的file控件元素支持多文件选择,其隐藏的玄机就是下面代码中大红高亮的部分:

dragDrop和upButton拖拽区域和上传按钮(默认隐藏):

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

urlAjax上传地址,没什么好说的,取的是表单的action地址:

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

filter方法对选择的文件进行过滤。file控件什么文件都能选,而demo页面是图片上传相关的demo;空间大小有限,超大尺寸的图片还是挡着为好。显然,要对上传文件进行过滤。于是,就有了如下的过滤脚本:

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('您这张"'+ file.name +'"图片大小过大,应小于500k'); 
      } else {
        arrFiles.push(file); 
      }  
    } else {
      alert('文件"' + file.name + '"不是图片。'); 
    }
  }
  return arrFiles;
}
Copy after login

zxxFile.js会自动对过滤后的文件对象列表进行整合,以准确上传。

onSelect方法文件(这里就是图片)选择后执行的方法。在本实例页面中,onSelect方法的主要任务就是本地图片在浏览器中的预览。本地图片上传之前在浏览器中预览的核心脚本就是:

var reader = new FileReader(), htmlImage;
reader.onload = function(e) {
  htmlImage = '<img src="&#39;+ e.target.result +&#39;" />';
}
reader.readAsDataURL(file);
Copy after login

在本demo页面中,该部分完成脚本如下,虽好像有些长度,其实内容就是装载一些HTML代码而已:

onSelect: function(files) {
  var html = '', i = 0;
  //等待载入gif动画
  $("#preview").html('<p class="upload_loading"></p>');
  var funAppendImage = function() {
    file = files[i];
    if (file) {
      var reader = new FileReader()
      reader.onload = function(e) {
        html = html + '<p id="uploadList_&#39;+ i +&#39;" class="upload_append_list"><p><strong>' + file.name + '</strong>'+ 
          '<a href="javascript:" class="upload_delete" title="删除" data-index="&#39;+ i +&#39;">删除</a><br />' +
          '<img id="uploadImage_&#39; + i + &#39;" src="&#39; + e.target.result + &#39;" class="upload_image" /></p>'+ 
          '<span id="uploadProgress_&#39; + i + &#39;" class="upload_progress"></span>' +
        '</p>';
        
        i++;
        funAppendImage();
      }
      reader.readAsDataURL(file);
    } else {
      //图片相关HTML片段载入
      $("#preview").html(html);
      if (html) {
        //删除方法
        $(".upload_delete").click(function() {
          ZXXFILE.funDeleteFile(files[parseInt($(this).attr("data-index"))]);
          return false; 
        });
        //提交按钮显示
        $("#fileSubmit").show(); 
      } else {
        //提交按钮隐藏
        $("#fileSubmit").hide(); 
      }
    }
  };
  //执行图片HTML片段的载人
  funAppendImage(); 
}
Copy after login

细心的你可能发现到上面的HTML元素中基本上都用到了i这个索引,作用是方便后面删除可以找到相应的元素。
然后,还有一个需要注意的就是删除事件——执行了ZXXFILE.funDeleteFile()方法,这是必须的,真正将图片从文件列表中删除,同时用来触发onDelete方法的回调。

onDelete方法图片上传完毕或是删除之时执行飞方法。本实例是让其渐隐:

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

onDragOver方法文件拖到拖拽元素上时执行的方法,本实例就是增加了个类名,如下:

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

onDragLeave方法文件移出元素上时执行的方法,本实例就是去掉了个类名,如下:

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

onProgress方法
上传中触发的方法。本demo效果就是图片左上角有个有着圆角黑色半透明背景元素,里面的百分比值不断增加。代码:

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

onSuccess方法当前图片上传成功后执行的方法。本demo就是提示返回的图片地址信息:

onSuccess: function(file, response) {
  $("#uploadInf").append(""<p>上传成功,图片地址是:" + response + ""</p>");
}
Copy after login

onFailure方法图片上传嗝屁时尿出的方法。本demo为提示,然后图片浅透明:

onFailure: function(file) {
  $("#uploadInf").append("<p>图片" + file.name + "上传失败!</p>"); 
  $("#uploadImage_" + file.index).css("opacity", 0.2);
}
Copy after login

onComplete方法当所有图片都上传完毕之后,本实例页面把file控件的value值置空,同时按钮隐藏了:

onComplete: function() {
  //提交按钮隐藏
  $("#fileSubmit").hide();
  //file控件value置空
  $("#fileImage").val("");
  $("#uploadInf").append("<p>当前图片全部上传完毕,可继续添加上传。</p>");
}
Copy after login

PHP页面相关代码

$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();
}
Copy after login

以上就是主要的些功能或交互代码。至于CSS样式部分以及HTML代码中的一些细节我就懒得捡芝麻了。您有兴趣可以通过查看源代码观摩观摩。

5. Current application scope of HTML5 file Ajax uploadNot only does IE browser not support it, but the latest Safari browser under win, or Opera do not fully support HTML5's previewable multi-image Ajax upload. So why are we still studying this? At least now there is no bird like this.

Indeed, in some of our external projects, it is too early to use this technology for web pages used by the majority of users. However, for the company's intranet project, it is absolutely OK to apply this. I discovered a very strange problem. Many times, intranet web pages support lower versions of IE, but do not support modern browsers. This is completely on the wrong track.

Recently, our company has started to reform the intranet project and started to develop the intranet based on modern browsers such as Chrome (of course, IE browser can also be used), and internal staff are forced to use Chrome browser. As far as our company is concerned, the response has been very good, whether it is UI effect, interaction or speed experience.

Obviously, at least in our company, if we want to provide a multi-image upload function for intranet editors or secretaries in the future, we can directly use HTML5 file upload, which is what this article is about. Simplicity, speed, and speed will make you realize that development is a happy and valuable thing.

In addition, the demo page of this article is more for examples, and I apologize for any mistakes in it. zxxFile.js has just been released and has not been practiced yet. Your valuable comments are welcome, thank you very much.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Ajax implements the function of file upload with progress bar effect

How to use readyState and status in Ajax

The above is the detailed content of How to create preview image effect with HTML5+ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? Mar 22, 2024 am 08:06 AM

With the continuous development of social media, Xiaohongshu has become a platform for more and more young people to share their lives and discover beautiful things. Many users are troubled by auto-save issues when posting images. So, how to solve this problem? 1. How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? 1. Clear the cache First, we can try to clear the cache data of Xiaohongshu. The steps are as follows: (1) Open Xiaohongshu and click the &quot;My&quot; button in the lower right corner; (2) On the personal center page, find &quot;Settings&quot; and click it; (3) Scroll down and find the &quot;Clear Cache&quot; option. Click OK. After clearing the cache, re-enter Xiaohongshu and try to post pictures to see if the automatic saving problem is solved. 2. Update the Xiaohongshu version to ensure that your Xiaohongshu

How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area? How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area? Mar 21, 2024 pm 09:12 PM

With the popularity of Douyin short videos, user interactions in the comment area have become more colorful. Some users wish to share images in comments to better express their opinions or emotions. So, how to post pictures in TikTok comments? This article will answer this question in detail and provide you with some related tips and precautions. 1. How to post pictures in Douyin comments? 1. Open Douyin: First, you need to open Douyin APP and log in to your account. 2. Find the comment area: When browsing or posting a short video, find the place where you want to comment and click the &quot;Comment&quot; button. 3. Enter your comment content: Enter your comment content in the comment area. 4. Choose to send a picture: In the interface for entering comment content, you will see a &quot;picture&quot; button or a &quot;+&quot; button, click

6 Ways to Make Pictures Sharper on iPhone 6 Ways to Make Pictures Sharper on iPhone Mar 04, 2024 pm 06:25 PM

Apple's recent iPhones capture memories with crisp detail, saturation and brightness. But sometimes, you may encounter some issues that may cause the image to look less clear. While autofocus on iPhone cameras has come a long way, allowing you to take photos quickly, the camera can mistakenly focus on the wrong subject in certain situations, making the photo blurry in unwanted areas. If your photos on your iPhone look out of focus or lack sharpness overall, the following post should help you make them sharper. How to Make Pictures Clearer on iPhone [6 Methods] You can try using the native Photos app to clean up your photos. If you want more features and options

How to make ppt pictures appear one by one How to make ppt pictures appear one by one Mar 25, 2024 pm 04:00 PM

In PowerPoint, it is a common technique to display pictures one by one, which can be achieved by setting animation effects. This guide details the steps to implement this technique, including basic setup, image insertion, adding animation, and adjusting animation order and timing. Additionally, advanced settings and adjustments are provided, such as using triggers, adjusting animation speed and order, and previewing animation effects. By following these steps and tips, users can easily set up pictures to appear one after another in PowerPoint, thereby enhancing the visual impact of the presentation and grabbing the attention of the audience.

What should I do if the images on the webpage cannot be loaded? 6 solutions What should I do if the images on the webpage cannot be loaded? 6 solutions Mar 15, 2024 am 10:30 AM

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.

How to use HTML, CSS and jQuery to implement advanced functions of image merging and display How to use HTML, CSS and jQuery to implement advanced functions of image merging and display Oct 27, 2023 pm 04:36 PM

Overview of advanced functions of how to use HTML, CSS and jQuery to implement image merge display: In web design, image display is an important link, and image merge display is one of the common techniques to improve page loading speed and enhance user experience. This article will introduce how to use HTML, CSS and jQuery to implement advanced functions of image merging and display, and provide specific code examples. 1. HTML layout: First, we need to create a container in HTML to display the merged images. You can use di

How to convert pdf documents into jpg images with Foxit PDF Reader - How to convert pdf documents into jpg images with Foxit PDF Reader How to convert pdf documents into jpg images with Foxit PDF Reader - How to convert pdf documents into jpg images with Foxit PDF Reader Mar 04, 2024 pm 05:49 PM

Are you also using Foxit PDF Reader software? So do you know how Foxit PDF Reader converts pdf documents into jpg images? The following article brings you how Foxit PDF Reader converts pdf documents into jpg images. For those who are interested in the method of converting jpg images, please come and take a look below. First start Foxit PDF Reader, then find "Features" on the top toolbar, and then select the "PDF to Others" function. Next, open a web page called "Foxit PDF Online Conversion". Click the "Login" button on the upper right side of the page to log in, and then turn on the "PDF to Image" function. Then click the upload button and add the pdf file you want to convert into an image. After adding it, click "Start Conversion"

How to arrange two pictures side by side in wps document How to arrange two pictures side by side in wps document Mar 20, 2024 pm 04:00 PM

When using WPS office software, we found that not only one form is used, tables and pictures can be added to the text, pictures can also be added to the table, etc. These are all used together to make the content of the entire document look richer. , if you need to insert two pictures into the document and they need to be arranged side by side. Our next course can solve this problem: how to place two pictures side by side in a wps document. 1. First, you need to open the WPS software and find the picture you want to adjust. Left-click the picture and a menu bar will pop up, select &quot;Page Layout&quot;. 2. Select &quot;Tight wrapping&quot; in text wrapping. 3. After all the pictures you need are confirmed to be set to &quot;Tight text wrapping&quot;, you can drag the pictures to the appropriate position and click on the first picture.

See all articles