How can I show a image preview in the browser without uploading the image file to the server?

前端 未结 2 1497
广开言路
广开言路 2020-12-05 11:14

In my application I want that when a user uploads an image file then I want to show the user the image immediately before submitting the form. This is so that they can previ

相关标签:
2条回答
  • 2020-12-05 11:55

    Since this was the first result for google("html5 image preview"), I thought I'd flesh out a contentful answer. I hope it's helpful.

    <img id="preview" src="placeholder.png" height="100px" width="100px" />
    <input type="file" name="image" onchange="previewImage(this)" accept="image/*"/>
    <script type="text/javascript">      
      function previewImage(input) {
        var preview = document.getElementById('preview');
        if (input.files && input.files[0]) {
          var reader = new FileReader();
          reader.onload = function (e) {
            preview.setAttribute('src', e.target.result);
          }
          reader.readAsDataURL(input.files[0]);
        } else {
          preview.setAttribute('src', 'placeholder.png');
        }
      }
    </script>
    
    0 讨论(0)
  • 2020-12-05 12:07

    It sure is possible with the HTML5 File API.

    0 讨论(0)
提交回复
热议问题