昨天帮同事整点bug,顺便花点时间研究了一下这个功能。
做个整理:
图片上传预览功能,目前通过了FF和IE测试。
jsp代码:
<div class="oa_frame_identity_test">
<table class="oa_identity_test_table">
<tr>
<td colspan="2"><center><span><font size="5px" color="red">请编辑您的文档</font></span></center></td>
</tr>
<tr>
<td align="center">基本资料</td>
<td>
<div><span>姓名:</span><span><input type="text" id="name" /></span></div>
<div><span>性别:</span><span><input type="radio" id="sex" name="sex" value="radiobutton" />男</span>
<span><input type="radio" id="sex" name="sex" value="radiobutton" />女</span></div>
</td>
</tr>
<tr>
<td align="center">上传照片</td>
<td><div><input type="file" id="img_select" οnchange="img_preview(this)" /></div>
<div id="img_show" float="left"><img id="img" style="display:none" src="<%=request.getContextPath() %>/images/Qdeath.gif" οnlοad="setPreviewSize(this)"/><img id="img_size" style="display:none"></div>
</td>
</tr>
</table>
</div>
js代码
this.setPreviewSize=function(img){
setSize(img,img.offsetWidth,img.offsetHeight);
}
this.img_preview=function(imgObj){
if(!imgObj.value.match(/.jpg|.gif|.png|.bmp/i)){
alert("图片格式无效!");
return false;
}
var imgSel=document.getElementById("img");
var imgDiv=document.getElementById("img_show");
var imgDivSize=document.getElementById("img_size");
if(imgObj.files||imgObj.files[0]){
imgSel.style.display="block";
imgSel.style.width="auto";
imgSel.style.height="auto";
//imgSel.src=imgObj.files[0].getAsDataURL;
//原本FF中取文件框的绝对路径,使用的是 getAsDataURL,在FF7及以上,getAsDataURL已经不再被支持了。
//FF7及以上使用var objectURL = window.URL.createObjectURL(fileObj);
imgSel.src=window.URL.createObjectURL(imgObj.files[0]);
}else if(imgDiv.filters){
// IE7,IE8 在设置本地图片地址为 img.src 时出现莫名其妙的后果
//(相同环境有时能显示,有时不显示),因此只能用滤镜来解决
// IE7, IE8因安全性问题已无法直接通过 input[file].value 获取完整的文件路径
imgObj.select();
var imgSrc=document.selection.createRange().text;//IE下获得file绝对路径
imgDiv.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=imgSrc;
imgDivSize.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=imgSrc;
imgSel.style.display="none";
}
}
this.test = function(){
console.log("come in");
}
//设置预览框大小。如果超出规定大小按比例缩放
function setSize(objPre,originalWidth,originalHeight){
var size = getSize( 128, 128, originalWidth, originalHeight );
objPre.style.width = size.width + 'px';
objPre.style.height = size.height + 'px';
objPre.style.marginTop = size.top + 'px';
objPre.style.marginLeft = size.left + 'px';
}
function getSize(maxWidth,maxHeight,Width,Height){
var param = { width:Width, height:Height, top:0, left:0 };
if( Width>maxWidth || Height>maxHeight ){
rateWidth = Width / maxWidth;
rateHeight = Height / maxHeight;
if( rateWidth > rateHeight ){
param.width = maxWidth;
param.height = Height / rateWidth;
}else{
param.width = Width / rateHeight;
param.height = maxHeight;
}
}
param.left = (maxWidth - param.width) / 2;
param.top = (maxHeight - param.height) / 2;
return param;
}
FF下效果图 IE下效果图
总结:js操作css滤镜问题,参考http://blog.csdn.net/lejuo/article/details/17557869