原文摘自:http://www.17sucai.com/preview/7442/2013-08-14/JS%E5%AE%9E%E7%8E%B0%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E5%8F%8A%E6%97%B6%E9%A2%84%E8%A7%88/index.html
做图片上传,由于是在一个弹框上修改图片,所以用的是ajax,也试过用fromdata,ajaxSubmit进行上传,结果总有兼容性的问题,所以放弃了先把图片上传到服务器上,然后回显。采用先获取本地机器上的图片,然后点击保存的时候再传图片。
代码如下:
<div class="pic" id="pic">
<!-- 这里的路径不应写死 要查库 -->
<img id="pimg" height="150" width="150" src="publicAction!do_downLoad.action?fId=${curPerson.headImg }">
<span style="visibility: hidden">点击修改</span>
<form id="uploadFileTop" name="uploadFileTop" enctype="multipart/form-data" method="post" action="personAction!do_uploadFile.action">
<input id="doUpload" type="file" name="file" οnchange="previewImage(this)" />
</form>
</div>
js如下:
//图片上传预览 IE是用了滤镜。
function previewImage(file) {
var MAXWIDTH = 260;
var MAXHEIGHT = 180;
var div = document.getElementById('pic');
if (file.files && file.files[0]) {
div.innerHTML = '<img id=pimg>';
var img = document.getElementById('pimg');
img.onload = function() {
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT,
img.offsetWidth, img.offsetHeight);
img.width = rect.width;
img.height = rect.height;
img.style.marginTop = rect.top + 'px';
}
var reader = new FileReader();
reader.onload = function(evt) {
img.src = evt.target.result;
}
reader.readAsDataURL(file.files[0]);
} else {
//IE
var sFilter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
file.select();
var src = document.selection.createRange().text;
if(document.selection.createRange().text){
div.innerHTML = '<img id=pimg>';
var img = document.getElementById('pimg');
img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth,
img.offsetHeight);
status = ('rect:' + rect.top + ',' + rect.left + ',' + rect.width
+ ',' + rect.height);
div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;"+sFilter+src+"\"'></div>";
}else{
alert("浏览器的安全模式过高,请在浏览器的Internet选项-安全");
}
}
}
function clacImgZoomParam(maxWidth, maxHeight, width, height) {
var param = {
top : 0,
left : 0,
width : width,
height : height
};
if (width > maxWidth || height > maxHeight) {
rateWidth = width / maxWidth;
rateHeight = height / maxHeight;
if (rateWidth > rateHeight) {
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
} else {
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
}
}
param.left = Math.round((maxWidth - param.width) / 2);
param.top = Math.round((maxHeight - param.height) / 2);
return param;
}
这样就可以获取到本地图片。但是你可能还是会获取失败,并且IE9报 document.selection.createRange() script无效。
这个时候看到网上有介绍的方法:1.在 var sFilter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="'; file.select();加divPreviewId
file.blur();修改为document.getElementById(divPreviewId).focus();divPreviewId是img标签外面的div的ID(这种方式没试过) 2:我调的是IE浏览器的安全模式,把安全模式设置为低就可以了。