问题
How can I able to preview a image before it is uploaded. The preview action should be executed in all browsers without using Ajax to upload the image.
Most of the examples are using FileReader, which wont work in IE9.
Is there any plugins or any alternative to make it working in IE9
f (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
回答1:
Here's the updated code. Hope it works for you.
if (input.files && input.files[0]) {
var url = URL.createObjectURL(input.files[0]);
$('#blah').attr('src', url);
}
回答2:
JavaScript:
$('#fileID').on('change',function(){ }
var imageName = '';
if (this.files && this.files.length > 0) {
imageName = this.files[0].name;
}
else if (this.value) {
imageName = this.value;
}
if (window.FileReader) {
//as same as other samples
}
else{
var image = document.getElementById('imgItem');
image.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale', src='" + imageName + "')";
image.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
}
//code end
I find this works well in emulation-IE9.
Another way to draw a image:
var canvas = document.getElementById('imgArea');
var img = new Image();
img.src = imageName;
img.onload = function () {
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, 200, 200);
}
Note: Add 2017/12/27
One solution to preview a local image with IE-9: IE-9 does`nt support FileReader, so I tried to upload it first then return the imageName(with server path) to View to change the 'src' attribute of the img. and it works well.
Points:(the example is using MVC)
1.In the 'change' event of input-type-file, do the ajaxSubmit(the action method:void)
2.In the Controller,using [Newtonsoft.Json.JsonConvert.SerializeObject],to return the json-formatted string.
Response.Write(strData);
3.In the callback of the ajaxSubmit, just change the src of the img. (dont forget convert the result to json)
来源:https://stackoverflow.com/questions/36388666/preview-an-image-in-div-before-its-uploaded-using-ie9