Home Web Front-end JS Tutorial Implementing image upload local preview function based on jquery_jquery

Implementing image upload local preview function based on jquery_jquery

May 16, 2016 pm 03:20 PM
jquery upload picture

When we upload files, if we have to upload them to the server every time before we can preview them, it seems reasonable but it is actually unreasonable. If the network speed is slow or there are problems with the pictures, this will not only waste customer time but also waste server resources. Okay, below we introduce the local preview when uploading images using js. I hope this method will be helpful to you.
1. Principle

is divided into two steps:

When the input for uploading an image is triggered and a local image is selected, obtain the URL of the object (object URL) of the image to be uploaded;

Assign the object URL to the src attribute of the pre-written img tag to display the image.

Here, we need to understand the File object, Blob object and window.URL.createObjectURL() method in Javascript.

1. File object

File object can be used to obtain information about a file, and can also be used to read the contents of this file. Usually, the File object is the FileList object returned after the user selects a file on an input element, or it can Is from the DataTransfer object generated by drag and drop operation.

Let’s look at getting the FileList object:

<script type="text/javascript" src="jquery.js"></script>

<input id="upload" type="file">
<img id="preview" src="">

<script type="text/javascript">
$('#upload').change(function(){
  // 获取FileList的第一个元素
  alert(document.getelementbyid('upload').files[0]);
});
</script>

Copy after login

2. Blob object

A Blob object is a file-like object containing read-only raw data. The data in the Blob object does not necessarily have to be in the native form in JavaScript. The File interface is based on Blob, inherits the functions of Blob, and extends support A local file on the user's computer.

The object URL we want to get is actually obtained from the Blob object, because the File interface inherits Blob. Let’s convert the Blob object into a URL:

<script type="text/javascript">
var f = document.getelementbyid('upload').files[0];
var src = window.URL.createObjectURL(f);
document.getElementById('preview').src = src;
</script>
Copy after login

A relatively complete example

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 Upload</title>
<style type="text/css">
    #destination{
      filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(true,sizingMethod=scale);
    }
</style>

<!--<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>-->
<script type="text/javascript" src="http://localhost/jQuery/jquery.js"></script>
<script type="text/javascript">
//处理file input加载的图片文件
$(document).ready(function(e) {
 //判断浏览器是否有FileReader接口
 if(typeof FileReader =='undefined')
 {
  $("#destination").css({'background':'none'}).html('亲,您的浏览器还不支持HTML5的FileReader接口,无法使用图片本地预览,请更新浏览器获得最好体验');
 //如果浏览器是ie
 if($.browser.msie===true)
 {
  //ie6直接用file input的value值本地预览
  if($.browser.version==6)
  {
    $("#imgUpload").change(function(event){   
    //ie6下怎么做图片格式判断&#63;
    var src = event.target.value;
    //var src = document.selection.createRange().text; //选中后 selection对象就产生了 这个对象只适合ie
    var img = '<img src="'+src+'" width="200px" height="200px" />';
    $("#destination").empty().append(img);
   });
  }
  //ie7,8使用滤镜本地预览
  else if($.browser.version==7 || $.browser.version==8)
  {
  $("#imgUpload").change(function(event){
    $(event.target).select();
    var src = document.selection.createRange().text;
    var dom = document.getElementById('destination');
    //使用滤镜 成功率高
    dom.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src= src;
    dom.innerHTML = '';
    //使用和ie6相同的方式 设置src为绝对路径的方式 有些图片无法显示 效果没有使用滤镜好
    /*var img = '<img src="'+src+'" width="200px" height="200px" />';
    $("#destination").empty().append(img);*/
   });
  }
 }
 //如果是不支持FileReader接口的低版本firefox 可以用getAsDataURL接口
 else if($.browser.mozilla===true)
 {
  $("#imgUpload").change(function(event){
  //firefox2.0没有event.target.files这个属性 就像ie6那样使用value值 但是firefox2.0不支持绝对路径嵌入图片 放弃firefox2.0
  //firefox3.0开始具备event.target.files这个属性 并且开始支持getAsDataURL()这个接口 一直到firefox7.0结束 不过以后都可以用HTML5的FileReader接口了
  if(event.target.files)
  {
   //console.log(event.target.files);
   for(var i=0;i<event.target.files.length;i++)
   { 
     var img = '<img src="'+event.target.files.item(i).getAsDataURL()+'" width="200px" height="200px"/>';
    $("#destination").empty().append(img);
   }
  }
  else
  {
   //console.log(event.target.value);
   //$("#imgPreview").attr({'src':event.target.value});
  }
  });
 }
 }
 else
 {
 // version 1
 /*$("#imgUpload").change(function(e){
  var file = e.target.files[0];
  var fReader = new FileReader();
  //console.log(fReader);
  //console.log(file);
  fReader.onload=(function(var_file)
  {
   return function(e)
   {
   $("#imgPreview").attr({'src':e.target.result,'alt':var_file.name});
   }
  })(file);
  fReader.readAsDataURL(file);
  });*/
  
  //单图上传 version 2 
  /*$("#imgUpload").change(function(e){
    var file = e.target.files[0];
    var reader = new FileReader(); 
  reader.onload = function(e){
   //displayImage($('bd'),e.target.result);
   //alert('load');
   $("#imgPreview").attr({'src':e.target.result});
  }
  reader.readAsDataURL(file);
   });*/
  //多图上传 input file控件里指定multiple属性 e.target是dom类型
   $("#imgUpload").change(function(e){ 
    for(var i=0;i<e.target.files.length;i++)
    {
     var file = e.target.files.item(i);
   //允许文件MIME类型 也可以在input标签中指定accept属性
   //console.log(/^image/.*$/i.test(file.type));
   if(!(/^image/.*$/i.test(file.type)))
   {
    continue;  //不是图片 就跳出这一次循环
   }
   
   //实例化FileReader API
   var freader = new FileReader();
   freader.readAsDataURL(file);
   freader.onload=function(e)
   {
    var img = '<img src="'+e.target.result+'" width="200px" height="200px"/>';
    $("#destination").empty().append(img);
   }
    }
   });
   
  //处理图片拖拽的代码
  var destDom = document.getElementById('destination');
  destDom.addEventListener('dragover',function(event){
   event.stopPropagation();
   event.preventDefault();
   },false);
   
  destDom.addEventListener('drop',function(event){
   event.stopPropagation();
   event.preventDefault();
   var img_file = event.dataTransfer.files.item(0);  //获取拖拽过来的文件信息 暂时取一个
   //console.log(event.dataTransfer.files.item(0).type);
   if(!(/^image/.*$/.test(img_file.type)))
   {
   alert('您还未拖拽任何图片过来,或者您拖拽的不是图片文件');
   return false;
   }
   fReader = new FileReader();
   fReader.readAsDataURL(img_file);
   fReader.onload = function(event){
   destDom.innerHTML='';
   destDom.innerHTML = '<img src="'+event.target.result+'" width="200px" height="200px"/>'; 
   };
  },false);
 }
});
</script>
</head>

<body>
<input type="file" id="imgUpload" name="imgUpload" draggable="true" single/> <!--允许file控件接受的文件类型-->
<!--<input type="file" id="imgUpload" name="imgUpload" accept="image/*" multiple/>-->
<div id="destination" style="width:200px;height:200px;border:1px solid #000000;"><img src="nopic.jpg" /></div>
</body>
</html>
Copy after login

2. Compatibility

  • •The above method is suitable for chrome browser
  • •If it is an IE browser, you can directly use the input value instead of src
  • • When viewing information online, you can directly use the getAsDataURL() method of the File object to obtain the URL. Now this method has been abolished. Similar methods include getAsText() and getAsBinary();

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

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)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

See all articles