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 u开发者_Go百科ser 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.
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>
It sure is possible with the HTML5 File API.
精彩评论