JS上傳前預覽圖片執行個體_javascript技巧

來源:互聯網
上載者:User

預覽圖片的js代碼:

複製代碼 代碼如下:

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


                //Firefox7以上版本不能用上面的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="yun_qi_img/logo.gif" width="300px" height="200px" />
</div>
   <asp:FileUpload ID="PicLoad" Width="300px" runat="server" onchange="javascript:setImagePreview(this,localImag,preview);">
   </asp:FileUpload>

  


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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.