asp.net頁面中實現如果圖片不存在則顯示預設圖片

來源:互聯網
上載者:User

在ASP.net開發中如果想要實現圖片找不到時顯示預設圖片的功能,我們有以下幾種方法:

1。js

可以獲得頁面上每個image標籤的對象。然後再設定它的src屬性就ok了。

代碼 <script>

   function window.onload() {     var img = document.getElementById("form1").getElementsByTagName("img")     for (var i = 0; i < img.length; i++) {         if (img[i].readyState == "uninitialized") {             img[i].src = "../images/defaultImage.bmp";         }     } }

</scirpt>

2.webconfig配置

在webconfig中配置可以簡便實用的解決一些棘手的問題。首先,每次解決方案的運行都要載入webconfig設定檔。我們可以寫個公用類來繼承IHttpHandler。在webconfig中配置 <httpHandlers> </httpHandlers>。

(1).類的方法

代碼     public ImageManager()     {         //         //TODO: 在此處添加建構函式邏輯         //     }      private const string DEFAULTIMAGE_URL = "DEFAULT.JPG";

    public bool IsReusable     {         get { return false; }     }

 

    public void ProcessRequest(HttpContext context)     {         //獲得請求的每個圖片的不同的物理地址         string imgPhysicalPath = context.Request.PhysicalPath;         System.Drawing.Image image = null;

if (File.Exists(imgPhysicalPath))         {                         //為空白

        }         else         {             //如果圖片不存在,放上預設的圖片             image = System.Drawing.Image.FromFile(context.Server.MapPath(DEFAULTIMAGE_URL));         }         //設定輸出的類型         context.Response.ContentType = "image/jpeg";         //把圖片儲存到輸出資料流裡         image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);         image.Dispose();

}

(2).webconfig配置

<add verb="*" path="路徑/*.jpg" type="公用類名"/>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.