Home > Web Front-end > H5 Tutorial > body text

Previewable multi-image Ajax upload based on HTML5

高洛峰
Release: 2017-02-17 17:08:17
Original
2191 people have browsed it

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 the "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, it can only be uploaded at one time. 1 picture can be uploaded 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 image drag and drop upload. 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):

Previewable multi-image Ajax upload based on HTML5

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

Previewable multi-image Ajax upload based on HTML5

Or you can directly drag the image on the desktop to accept Drag area:

Previewable multi-image Ajax upload based on HTML5

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

Previewable multi-image Ajax upload based on HTML5

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

Previewable multi-image Ajax upload based on HTML5

The page address after uploading is returned, as follows:

Previewable multi-image Ajax upload based on HTML5

At this time, the corresponding upload There is this picture under the folder:

Previewable multi-image Ajax upload based on HTML5

Note: The space of my blog is limited, I will clean up the picture folder regularly, so please don’t This is a free image hosting place~~

3. Simple analysis of the core skeleton script
The first is a core file uploaded, which was slowly swallowed two nights ago Completed. The file name is: zxxFile.js (you can right-click... to download)

This file is only a few KB 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 their corresponding content and meaning, etc.

Previewable multi-image Ajax upload based on HTML5

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.

显然,只有骨架基本上做不了什么事件。demo页面之所以有效果,就是其按照上面的骨架,根据实际的需求增加了血肉。您可以直接“右键-查看页面源代码”一览所有相关JavaScript。或者看我下面一点一点婆妈的讲述。

我们按照上面表格中的骨架进行示意。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

url
Ajax上传地址,没什么好说的,取的是表单的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 = &#39;<img  src="&#39;+ e.target.result +&#39;" / alt="Previewable multi-image Ajax upload based on HTML5" >&#39;;
}
reader.readAsDataURL(file);
Copy after login

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

onSelect: function(files) {
  var html = &#39;&#39;, i = 0;
  //等待载入gif动画
  $("#preview").html(&#39;<p class="upload_loading"></p>&#39;);
  var funAppendImage = function() {
    file = files[i];
    if (file) {
      var reader = new FileReader()
      reader.onload = function(e) {
        html = html + &#39;<p id="uploadList_&#39;+ i +&#39;" class="upload_append_list"><p><strong>&#39; + file.name + &#39;</strong>&#39;+ 
          &#39;<a href="javascript:" class="upload_delete" title="删除" data-index="&#39;+ i +&#39;">删除</a><br />&#39; +
          &#39;<img  id="uploadImage_&#39; + i + &#39;" src="&#39; + e.target.result + &#39;" class="upload_image" / alt="Previewable multi-image Ajax upload based on HTML5" ></p>&#39;+ 
          &#39;<span id="uploadProgress_&#39; + i + &#39;" class="upload_progress"></span>&#39; +
        &#39;</p>&#39;;
        
        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) + &#39;%&#39;;
  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[&#39;HTTP_X_FILENAME&#39;]) ? $_SERVER[&#39;HTTP_X_FILENAME&#39;] : false);
if ($fn) {
  file_put_contents(
    &#39;uploads/&#39; . $fn,
    file_get_contents(&#39;php://input&#39;)
  );
  echo "http://www.zhangxinxu.com/study/201109/uploads/$fn";
  exit();
}
Copy after login

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

5. Current application scope of HTML5 file Ajax upload
Not only is it not supported by IE, but the latest Safari browser under win, or Opera do not fully support HTML5's multiple image previews Ajax upload, then why should we learn this? At least now there is no bird like this.

Indeed, for 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. We 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.

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to HTML5-based previewable multi-image Ajax upload, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!