DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> JS上傳前預覽圖片實例
JS上傳前預覽圖片實例
編輯:關於JavaScript     

預覽圖片的js代碼:

復制代碼 代碼如下:
<script type="text/javascript">
        function setImagePreview(docObj,localImagId,imgObjPreview)
        {
            if(docObj.files && docObj.files[0])
            {
                //火狐下,直接設img屬性
                imgObjPreview.style.display = 'block';
                imgObjPreview.style.width = '300px';
                imgObjPreview.style.height = '200px';                   


                //火狐7以上版本不能用上面的getAsDataURL()方式獲取,需要一下方式 
                imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
            }
            else
            {
                //IE下,使用濾鏡
                docObj.select();
                var imgSrc = document.selection.createRange().text;

                //必須設置初始大小
                localImagId.style.width = "300px";
                localImagId.style.height = "200px";

                //圖片異常的捕捉,防止用戶修改後綴來偽造圖片
                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>

fileupload控件及用來預覽圖片的image:

復制代碼 代碼如下:
<div id="localImag"  style="width: 300px; height: 200px">
   <img id="preview" alt="預覽圖片" src="http://www.jb51.net/images/logo.gif" width="300px" height="200px" />
</div>
   <asp:FileUpload ID="PicLoad" Width="300px" runat="server" onchange="javascript:setImagePreview(this,localImag,preview);">
   </asp:FileUpload>

  
功能很簡單,代碼也很易懂,相信不用我多廢話大家也能看懂吧。感覺寫這樣的文章,真的沒啥好說的,不多說,還是把重點放在代碼上吧。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved