How to generate a thumbnail image after adding an image inside an input type=“file” in a form and submitting them both on the same form

后端 未结 5 959
误落风尘
误落风尘 2020-11-30 19:58

I have a form which allows the user to upload a picture. After the user has submitted the form, I\'d like to generate on the front-end a thumbnail for each picture and then

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 20:39

    I found This simpler yet powerful tutorial. It simply creates an img element and, using the fileReader object, assigns its source attribute as the value of the form input

    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 = "";
      }
    }

    Image preview...

提交回复
热议问题