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 986
误落风尘
误落风尘 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:32

    Thought it might be worth adding a more contemporary answer and citing MDN Web Docs.

    You can add an event listener for "change" on the input element and then show a thumbnail of the selected image by accessing the file list through this.files (as shown in an MDN examples). Here is a recent implementation of mine. uploadWatermark is an

    uploadWatermark.addEventListener('change', function(){
      const file = this.files[0];
      if (file.type.startsWith('image/')) {
        const img = document.createElement('img');
        const watermarkPreview = document.getElementById("uploaded-watermark");
    
        img.classList.add("prev-thumb");
        img.file = file;
        watermarkPreview.appendChild(img);
    
        const reader = new FileReader();
        reader.onload = (function(aImg) { return function(e) { aImg.src =   e.target.result; }})(img);
        reader.readAsDataURL(file);
      }
      
    });

提交回复
热议问题