Js implements input to upload images and display thumbnails

Using this method, you can easily and quickly realize the effect of uploading pictures and displaying thumbnails:

FileReader 的 readAsDataURL()

First create an img tag, and then use fileReader to assign the input file to the src of img

The specific code is as follows:

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    preview.src = reader.result;
  }

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
}
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325347429&siteId=291194637