使用JQuery创建图像的实时预览(在上传之前) [英] Create live preview of image (before upload it) using JQuery
问题描述
我想在使用JQuery将其上传到服务器上之前创建图像预览。
I want to create a preview for image before upload it on the server, using JQuery.
我的代码,js代码:
$(function(){
Test = {
UpdatePreview: function(obj){
// if IE < 10 doesn't support FileReader
if(!window.FileReader){
// don't know how to proceed to assign src to image tag
} else {
var reader = new FileReader();
var target = null;
reader.onload = function(e) {
target = e.target || e.srcElement;
$("img").prop("src", target.result);
};
reader.readAsDataURL(obj.files[0]);
}
}
};
});
我的html:
<input type='file' name='browse' onchange='Test.UpdatePreview(this)' />
<br/><br/>
<img src="#" alt="test" width="128" height="128" />
请参阅jsfiddle: http ://jsfiddle.net/aAuMU/
See jsfiddle: http://jsfiddle.net/aAuMU/
在 onload
之后,我看到图像的src (使用谷歌控制台应用程序),它看起来像:
After onload
, I see the src of image (using Google console application) and it looks like:
data:image / jpeg; base64,/ 9j / 4AAQSkZJRgABAgAAAQABAAD // gAEKgD / 4gv4SUNDX1BST0ZJTEUAAQEAAAvoAAAAAAAAAAAAADAABA ..
如果我使用IE作为浏览器,这是一种在javascript中获取图像基础并分配给图像的方法吗?
It is a way to get in javascript the base of image and assign to image in case I'm using IE as browser ?
FileReader
在IE中不起作用< 10。
FileReader
doesn't work in IE < 10.
推荐答案
如果你需要它可以获得很好的效果那么你可以像在
中那样使用闪光灯 https://github.com/mailru/FileAPI
If you need it as getting nice effect then you could use flash like they do in https://github.com/mailru/FileAPI
但是当我需要向用户显示图像时,因为我需要让用户选择区域进行裁剪,然后我使用隐藏iframe中的表单并将图像上传到服务器并发回图像数据uri,这样我就可以获取数据uri并替换图像src属性,然后当选择区域时,我没有将图像作为文件发回,而是作为数据uri发送。在旧的浏览器中,它意味着您上传图像两次,但我不想使用闪存,因为在某些情况下也可能无法安装闪存。
But when i needed to show image to user because i needed to let user select area for croping then i used form inside hidden iframe and uploaded image to server and sent back image data uri so i was able to get data uri and replace image src attribute, then when area was selected i did not send image back as file but as data uri. In old browsers it means you upload image twice, but i did not want to use flash as in some cases flash may also not be installed there.
这篇关于使用JQuery创建图像的实时预览(在上传之前)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!