js图片预览添加看不到图片

JavaScript016

js图片预览添加看不到图片,第1张

在页面中,添加一个没有指定图片路径的img标签,通过js给img图片设置路径 在IE浏览器中运行效果如图所示,图片正常显示了 图片不显示,首先检查js是否找到了正确的dom对象,然后设置图片路径 ...

芝士回答2022-03-06

无需插件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<title>By:DragonDean</title>

<script type="text/javascript">

//下面用于图片上传预览功能

function setImagePreview(avalue) {

var docObj=document.getElementById("doc")

var imgObjPreview=document.getElementById("preview")

if(docObj.files &&docObj.files[0])

{

//火狐下,直接设img属性

imgObjPreview.style.display = 'block'

imgObjPreview.style.width = '150px'

imgObjPreview.style.height = '180px'

//imgObjPreview.src = docObj.files[0].getAsDataURL()

//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式

imgObjPreview.src = window.URL.createObjectURL(docObj.files[0])

}

else

{

//IE下,使用滤镜

docObj.select()

var imgSrc = document.selection.createRange().text

var localImagId = document.getElementById("localImag")

//必须设置初始大小

localImagId.style.width = "150px"

localImagId.style.height = "180px"

//图片异常的捕捉,防止用户修改后缀来伪造图片

try{

localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)"

localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc

}

catch(e)

{

alert("您上传的图片格式不正确,请重新选择!")

return false

}

imgObjPreview.style.display = 'none'

document.selection.empty()

}

return true

}

</script>

</head>

<body>

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tbody>

<tr>

<td height="101" align="center">

<div id="localImag"><img id="preview" src="http://blog.chuangling.net/Public/images/top.jpg" width="150" height="180" style="display: blockwidth: 150pxheight: 180px"></div>

</td>

</tr>

<tr>

<td align="center" style="padding-top:10px"><input type="file" name="file" id="doc" style="width:150px" onchange="javascript:setImagePreview()"></td>

</tr>

</tbody>

</table>

</body>

</html>

jQuery File Upload是上传文件的一个插件,不一定是图片,所以里面没做预览的支持。但是可以直接用jquery简单实现出来,代码如下:

/*

先在js里扩展一个uploadPreview方法

使用方法: 

<div>

<img id="ImgPr" width="120" height="120" /></div>

<input type="file" id="up" />

把需要进行预览的IMG标签外 套一个DIV 然后给上传控件ID给予uploadPreview事件

$("#up").uploadPreview({ Img: "ImgPr", Width: 120, Height: 120, ImgType: ["gif", "jpeg", "jpg", "bmp", "png"], Callback: function () { }})

*/

jQuery.fn.extend({

    uploadPreview: function (opts) {

        var _self = this,

            _this = $(this)

        opts = jQuery.extend({

            Img: "ImgPr",

            Width: 100,

            Height: 100,

            ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],

            Callback: function () {}

        }, opts || {})

        _self.getObjectURL = function (file) {

            var url = null

            if (window.createObjectURL != undefined) {

                url = window.createObjectURL(file)

            } else if (window.URL != undefined) {

                url = window.URL.createObjectURL(file)

            } else if (window.webkitURL != undefined) {

                url = window.webkitURL.createObjectURL(file)

            }

            return url

        }

        _this.change(function () {

            if (this.value) {

                if (!RegExp("\.(" + opts.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {

                    alert("选择文件错误,图片类型必须是" + opts.ImgType.join(",") + "中的一种")

                    this.value = ""

                    return false

                }

                if ($.browser.msie) {

                    try {

                        $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))

                    } catch (e) {

                        var src = ""

                        var obj = $("#" + opts.Img)

                        var div = obj.parent("div")[0]

                        _self.select()

                        if (top != self) {

                            window.parent.document.body.focus()

                        } else {

                            _self.blur()

                        }

                        src = document.selection.createRange().text

                        document.selection.empty()

                        obj.hide()

                        obj.parent("div").css({

                            'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',

                            'width': opts.Width + 'px',

                            'height': opts.Height + 'px'

                        })

                        div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src

                    }

                } else {

                    $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))

                }

                opts.Callback()

            }

        })

    }

})

然后是HTML页面进行调用:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>图片上传预览演示</title>

<script src="jquery.min.js" type="text/javascript"></script>

<script src="16/uploadPreview.js" type="text/javascript"></script>

<script>

$(function () {

$("#up").uploadPreview({ Img: "ImgPr", Width: 120, Height: 120 })

})

</script>

</head>

<body>

<div style="width:500pxmargin:0px auto"><h2>图片上传预览演示</h2>

<div><img id="ImgPr" width="120" height="120" /></div>

<input type="file" id="up" />

</div>

</body>

</html>