Html 如何在不将图像文件上传到服务器的情况下在浏览器中显示图像预览?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5256620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I show a image preview in the browser without uploading the image file to the server?
提问by Seth Battin
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?
在 HTML5 中,文件上传器是否可以在提交实际表单之前在客户端显示图像?
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.
我想允许用户预览图像文件而不将文件上传到服务器(因此也没有上传到临时目录),但不知何故只是在客户端浏览器的客户端显示图像。
采纳答案by Jeremy Conley
It sure is possible with the HTML5 File API.
使用HTML5 File API肯定是可能的。
回答by Seth Battin
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.
由于这是 的第一个结果google("html5 image preview")
,我想我会充实一个内容丰富的答案。我希望它有帮助。
<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>