HTML - 选择文件名后显示图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12368910/
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
HTML - Display image after selecting filename
提问by Edward Hasted
I have a form that allows me with
我有一个表格可以让我
<input type="file" name="filename" accept="image/gif, image/jpeg, image/png">
to browse and select a file.
浏览并选择一个文件。
What I want to do is display that image immediately after the image has been selected. And this is before the "submit" button on the form has been pressed so the image almost certainly resides Client side. Can this be done?
我想要做的是在选择图像后立即显示该图像。这是在按下表单上的“提交”按钮之前,因此图像几乎可以肯定位于客户端。这能做到吗?
回答by ygssoni
Here You Go:
干得好:
HTML
HTML
<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
Script:
脚本:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
回答by Xavier
You can achieve this with the following code:
您可以使用以下代码实现此目的:
$("input").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("input").after(img);
}
});
回答by Kelvin
This can be done using HTML5, but will only work in browsers that support it. Here's an example.
这可以使用 HTML5 来完成,但只能在支持它的浏览器中工作。这是一个例子。
Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.
请记住,对于不支持此功能的浏览器,您需要另一种方法。我在这个插件上取得了很大的成功,它可以让您免去很多工作。