Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

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

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 preview the image before they submit the form.

Is there any way in HTML5 that the file uploader can show the image on the client side before the actual form is submitted?

I want to allow the user to preview the image file without uploading the file to the server (so no uploading to the temp directory either), but somehow just show the image on the client side in the client browser.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...