图片上传及本地预览

今天在做后台项目的时候,需要用到图片上传功能。因为功能不是很复杂,对图片上传的要求也不是很高,所以并没有使用上传插件(uploadify),而是直接使用 input[type="file"] 的传统方式。再加上要在前端做一个选择图片后的本地图片预览功能(兼容IE)。所以就有了以下实现代码。

Html代码:

1
2
<input type="file" name="file" id="file" />
<div id="prewrap"><img id="preimg" style="diplay:none" /></div>

Js脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var file=document.getElementById("file");
var preimg=document.getElementById("preimg");
if(file.files&&file.files[0]){
    preimg.style.display = 'block';
    preimg.style.width = '300px';
    preimg.style.height = '150px';                    
    preimg.src = window.URL.createObjectURL(file.files[0]);
}else{
    file.select();
    file.blur(); //这个为必需,不加在IE中报Script错误
    var ieimg = document.selection.createRange().text;
    var prewrap = document.getElementById("prewrap");
    prewrap.style.width = "300px";
    prewrap.style.height = "150px";
    try{
        prewrap.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
        prewrap.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = ieimg;
    }catch(e){
        alert("图片格式不正确,请重新选择!");
        return false;
    }
    preimg.style.display = 'none';
    document.selection.empty();
}

最后如果有多个预览控件时,在重新打开控件的时候,记得把input[type=”file”]的值进行清空。不然下次选择相同的文件时是不会出现预览效果的。

因为平常的file控件外观不好看,经常需要根据设计来进行修改。下面提供一种实现方法,原理是修改控件的透明度,然后用Ui效果展示。

1
2
3
4
<span style="position:relative;display:inline-block;">
<input type="file" accept=".jpg" id="filebtn" style="position: absolute;top: 0;left: 0;filter: alpha(opacity:0);opacity: 0;width: 88px;height:30px;" name="filebtn" value="选择图片 ">
<a href="javascript:;" class="select-pic">选择图片</a>
</span>

这样,通过修改select-pic的样式,来达到想要的Ui效果。