首页 > 代码库 > 图片上传预览

图片上传预览

Js脚本页面

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>js上传图片预览</title>
</head>
<script type="text/javascript">

    //下面用于多图片上传预览功能
    function setImagePreviews(avalue) {
        //获取选择图片的对象
        var docObj = document.getElementById("doc");
        //后期显示图片区域的对象
        var dd = document.getElementById("dd");
        dd.innerHTML = "";
        //得到所有的图片文件
        var fileList = docObj.files;
        //循环遍历
        for (var i = 0; i < fileList.length; i++) {    
            //动态添加html元素        
            dd.innerHTML += "<div style=‘float:left‘ > <img id=‘img" + i + "‘  /> </div>";
            //获取图片imgi的对象
            var imgObjPreview = document.getElementById("img"+i); 
            
            if (docObj.files && docObj.files[i]) {
                //火狐下,直接设img属性
                imgObjPreview.style.display = ‘block‘;
                imgObjPreview.style.width = ‘200px‘;
                imgObjPreview.style.height = ‘180px‘;
                //imgObjPreview.src = http://www.mamicode.com/docObj.files[0].getAsDataURL();"img" + i);
               //必须设置初始大小
                localImagId.style.width = "200px";
                localImagId.style.height = "180px";
                //图片异常的捕捉,防止用户修改后缀来伪造图片
                try {
                    localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                    localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = http://www.mamicode.com/imgSrc;"您上传的图片格式不正确,请重新选择!");
                    return false;
                }
                imgObjPreview.style.display = ‘none‘;
                document.selection.empty();
            }
        }  
        return true;
    }

</script>







html页面

 
<body>
    <div style="margin :0px auto; width:990px;">
        <input type="file"  name="file" id="doc" multiple="multiple"  style="width:150px;" onchange="javascript:setImagePreviews();" accept="image/*" />
        <div id="dd" style=" width:990px;"></div>
    </div>
</body>
</html>
 

图片上传预览