Javascript 从 <input file> 加载图像到 <img>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3814231/
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
Loading an image to a <img> from <input file>
提问by Valentina
I'm trying to load an image selected by the user through an element.
我正在尝试通过元素加载用户选择的图像。
I added a onchange event handler to the input element like this:
我向输入元素添加了一个 onchange 事件处理程序,如下所示:
<input type="file" name="picField" id="picField" size="24" onchange="preview_2(this);" alt=""/>
and the preview_2 function is:
和 preview_2 功能是:
var outImage ="imagenFondo";
function preview_2(what){
globalPic = new Image();
globalPic.onload = function() {
document.getElementById(outImage).src = globalPic.src;
}
globalPic.src=what.value;
}
where outImage has the id value of the tag where I want the new picture to be loaded.
其中 outImage 具有我希望加载新图片的标签的 id 值。
However, it appears that the onload never happens and it does not load anything to the html.
但是,似乎 onload 永远不会发生并且它不会将任何内容加载到 html。
What should I do?
我该怎么办?
回答by Andy E
In browsers supporting the File API, you can use the FileReaderconstructor to read files once they have been selected by the user.
在支持File API 的浏览器中,一旦用户选择了文件,您就可以使用FileReader构造函数读取文件。
Example
例子
document.getElementById('picField').onchange = function (evt) {
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
// FileReader support
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
document.getElementById(outImage).src = fr.result;
}
fr.readAsDataURL(files[0]);
}
// Not supported
else {
// fallback -- perhaps submit the input to an iframe and temporarily store
// them on the server until the user's session ends.
}
}
Browser support
浏览器支持
- IE 10
- Safari 6.0.2
- Chrome 7
- Firefox 3.6
- Opera 12.02
- 浏览器 10
- Safari 6.0.2
- 铬 7
- 火狐 3.6
- 歌剧 12.02
Where the File API is unsupported, you cannot (in most security conscious browsers) get the full path of a file from a file input box, nor can you access the data. The only viable solution would be to submit the form to a hidden iframe and have the file pre-uploaded to the server. Then, when that request completes you could set the src of the image to the location of the uploaded file.
在不支持 File API 的情况下,您无法(在大多数具有安全意识的浏览器中)从文件输入框中获取文件的完整路径,也无法访问数据。唯一可行的解决方案是将表单提交到隐藏的 iframe 并将文件预先上传到服务器。然后,当该请求完成时,您可以将图像的 src 设置为上传文件的位置。
回答by Mike Morearty
As iEamin said in his answer, HTML 5 does now support this. The link he gave, http://www.html5rocks.com/en/tutorials/file/dndfiles/, is excellent. Here is a minimal sample based on the samples at that site, but see that site for more thorough examples.
正如 iEamin 在他的回答中所说,HTML 5 现在确实支持这一点。他提供的链接http://www.html5rocks.com/en/tutorials/file/dndfiles/非常好。这是基于该站点示例的最小示例,但请参阅该站点以获取更全面的示例。
Add an onchange
event listener to your HTML:
将onchange
事件侦听器添加到您的 HTML:
<input type="file" onchange="onFileSelected(event)">
Make an image tag with an id (I'm specifying height=200
to make sure the image isn't too huge onscreen):
制作带有 id 的图像标签(我指定height=200
确保图像在屏幕上不会太大):
<img id="myimage" height="200">
Here is the JavaScript of the onchange
event listener. It takes the File
object that was passed as event.target.files[0]
, constructs a FileReader
to read its contents, and sets up a new event listener to assign the resulting data:
URL to the img
tag:
这是onchange
事件侦听器的 JavaScript 。它接受File
作为 传递的对象event.target.files[0]
,构造 aFileReader
以读取其内容,并设置一个新的事件侦听器以将结果data:
URL分配给img
标签:
function onFileSelected(event) {
var selectedFile = event.target.files[0];
var reader = new FileReader();
var imgtag = document.getElementById("myimage");
imgtag.title = selectedFile.name;
reader.onload = function(event) {
imgtag.src = event.target.result;
};
reader.readAsDataURL(selectedFile);
}
回答by asghar
$('document').ready(function () {
$("#imgload").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgshow').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="imgload" >
<img src="#" id="imgshow" align="left">
回答by Mike Morearty
Andy E is correct that there is no HTML-based way to do this*; but if you are willing to use Flash, you can do it. The following works reliably on systems that have Flash installed. If your app needs to work on iPhone, then of course you'll need a fallback HTML-based solution.
Andy E 是正确的,没有基于 HTML 的方法可以做到这一点*;但如果你愿意使用 Flash,你可以做到。以下内容在安装了 Flash 的系统上可靠运行。如果您的应用程序需要在 iPhone 上运行,那么您当然需要一个基于 HTML 的后备解决方案。
* (Update 4/22/2013:HTML does now support this, in HTML5. See the other answers.)
*(更新 4/22/2013:HTML 现在在 HTML5 中支持此功能。请参阅其他答案。)
Flash uploading also has other advantages -- Flash gives you the ability to show a progress bar as the upload of a large file progresses. (I'm pretty sure that's how Gmail does it, by using Flash behind the scenes, although I may be wrong about that.)
Flash 上传还有其他优点——Flash 使您能够在上传大文件时显示进度条。(我很确定 Gmail 就是这样做的,在幕后使用 Flash,虽然我可能错了。)
Here is a sample Flex 4 app that allows the user to pick a file, and then displays it:
这是一个示例 Flex 4 应用程序,它允许用户选择一个文件,然后显示它:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="init()">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
<mx:Image id="myImage" x="9" y="44"/>
<fx:Script>
<![CDATA[
private var fr:FileReference = new FileReference();
// Called when the app starts.
private function init():void
{
// Set up event handlers.
fr.addEventListener(Event.SELECT, onSelect);
fr.addEventListener(Event.COMPLETE, onComplete);
}
// Called when the user clicks "Choose file..."
private function showFilePicker():void
{
fr.browse();
}
// Called when fr.browse() dispatches Event.SELECT to indicate
// that the user has picked a file.
private function onSelect(e:Event):void
{
fr.load(); // start reading the file
}
// Called when fr.load() dispatches Event.COMPLETE to indicate
// that the file has finished loading.
private function onComplete(e:Event):void
{
myImage.data = fr.data; // load the file's data into the Image
}
]]>
</fx:Script>
</s:Application>
回答by nkitku
ES6 way
ES6方式
const readURL = file => {
return new Promise((res, rej) => {
const reader = new FileReader();
reader.onload = e => res(e.target.result);
reader.onerror = e => rej(e);
reader.readAsDataURL(file);
});
};
const preview = async event => {
const file = event.target.files[0];
const url = await readURL(file);
img.src = url;
};
回答by Saeed saeeyd
var outImage ="imagenFondo";
function preview_2(obj)
{
if (FileReader)
{
var reader = new FileReader();
reader.readAsDataURL(obj.files[0]);
reader.onload = function (e) {
var image=new Image();
image.src=e.target.result;
image.onload = function () {
document.getElementById(outImage).src=image.src;
};
}
}
else
{
// Not supported
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>preview photo</title>
</head>
<body>
<form>
<input type="file" onChange="preview_2(this);"><br>
<img id="imagenFondo" style="height: 300px;width: 300px;">
</form>
</body>
</html>