Based on jquery image upload local preview function

  • 2020-11-26 18:43:07
  • OfStack

If every time when we in the upload file to be uploaded to the server can preview the do look reasonable is unreasonable, if there is something wrong with the network speed is slow or pictures, such not only waste the customer time and at the same time wasting server resources, here we introduce using local when js upload pictures for preview, hope this way help you oh.
Principle 1.

There are two steps:

Get URL (object URL) of the image to be uploaded when input is triggered and the local image is selected.

The image is displayed by assigning the object URL to the src attribute of the prewritten img tag.

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

1. File object

The File object can be used to get information about a file and can also be used to read the contents of that file. Typically, the File object is the FileList object returned after the user selects a file on an input element, or it can be an DataTransfer object generated by a 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(){
  //  To obtain FileList The first 1 An element 
  alert(document.getelementbyid('upload').files[0]);
});
</script>

2. Blob object

An Blob object is a class file object that contains read-only raw data. The data in the Blob object is not specified as the native form in JavaScript. The File interface is based on Blob, inherits the functions of Blob, and extends support for local files on the user's computer.

The object we want, URL, is actually derived from the object Blob, because File's interface inherits Blob. Let's convert the Blob object to URL:


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

A more 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">
// To deal with file input The image file to load 
$(document).ready(function(e) {
 // Determine if the browser has one FileReader interface 
 if(typeof FileReader =='undefined')
 {
  $("#destination").css({'background':'none'}).html(' Pro - , Your browser does not support it yet HTML5 the FileReader interface , Unable to use image local preview , Please update your browser for the best possible experience ');
 // If the browser is ie
 if($.browser.msie===true)
 {
  //ie6 Use directly file input the value Value local preview 
  if($.browser.version==6)
  {
    $("#imgUpload").change(function(event){   
    //ie6 How to make image format judgment ?
    var src = event.target.value;
    //var src = document.selection.createRange().text; // After the selected  selection The object is generated   This object only fits ie
    var img = '<img src="'+src+'" width="200px" height="200px" />';
    $("#destination").empty().append(img);
   });
  }
  //ie7,8 Use filter local preview 
  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');
    // Use a filter   High success rate 
    dom.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src= src;
    dom.innerHTML = '';
    // The use and ie6 The same way   Set up the src The way for the absolute path   Some images cannot be displayed   The effect is not as good as using a filter 
    /*var img = '<img src="'+src+'" width="200px" height="200px" />';
    $("#destination").empty().append(img);*/
   });
  }
 }
 // If it is not supported FileReader A lower version of the interface firefox  You can use getAsDataURL interface 
 else if($.browser.mozilla===true)
 {
  $("#imgUpload").change(function(event){
  //firefox2.0 There is no event.target.files This attribute   Just like ie6 use value value   but firefox2.0 Absolute path embedding of images is not supported   To give up firefox2.0
  //firefox3.0 Start with event.target.files This attribute   And start supporting getAsDataURL() This interface  1 until firefox7.0 The end of the   But you can use it in the future HTML5 the FileReader The interface 
  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);
  });*/
  
  // Upload a single chart  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);
   });*/
  // Upload photos  input file Specified in the control multiple attribute  e.target is dom type 
   $("#imgUpload").change(function(e){ 
    for(var i=0;i<e.target.files.length;i++)
    {
     var file = e.target.files.item(i);
   // Allows documents MIME type   Can also be input Specified in the label accept attribute 
   //console.log(/^image/.*$/i.test(file.type));
   if(!(/^image/.*$/i.test(file.type)))
   {
    continue;  // Not pictures   Out of this 1 loops 
   }
   
   // instantiation 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);
   }
    }
   });
   
  // Handle the picture drag and drop code 
  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);  // Gets the file information that you drag and drop   Temporarily take 1 a 
   //console.log(event.dataTransfer.files.item(0).type);
   if(!(/^image/.*$/.test(img_file.type)))
   {
   alert(' You haven't dragged any images over yet , Or you're not dragging an image file ');
   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/> <!-- allow file Control to accept the type of 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>

2. The compatibility

The & # 8226; The above method works for the chrome browser The & # 8226; If you are using IE, you can use value instead of src The & # 8226; The getAsDataURL() method of File object has been used to obtain URL, but this method has been abolished. Similar methods are getAsText() and getAsBinary().

Above is the entire content of this article, I hope to help you with your study.


Related articles: