<img>標籤顯示本地路徑的圖片的.NET解決方案

來源:互聯網
上載者:User

標籤:

    今天朋友問了我一個奇怪的需求:項目中要求圖片上傳到工作目錄,上傳後要在網頁中通過<img>顯示出來。圖片上傳後顯示,在開發中常見的做法是將它圖片上傳到網站目錄下(upload/),如果儲存到別的目錄(如:d:/upload),再用<img src="d:/upload/xxx.jpg"> 是找不到圖片的。

想到了兩種解決方案:

第一種:給路徑加上"file://" (File協議主要用於訪問本機電腦中的檔案),目前只有ie下能正常顯示

<img src="file:///d:/upload/xxx.jpg" />

第二種做法:建立一般處理常式(ShowLocalImg.ashx) ,再調用context.Response.WriteFile()

以下部分程式碼範例:

 Upload.html

<html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title></head><body><form action="Upload.ashx" method="post" enctype="multipart/form-data"><input type="file" name="pic" /><input type="submit" value="Upload" /></form></body></html>

 Upload.ashx

public void ProcessRequest(HttpContext context)
  {context.Response.ContentType = "text/html";HttpPostedFile file = context.Request.Files["pic"];     if (file != null){  String filePath = "c:/upload/" + file.FileName;  file.SaveAs( filePath );  context.Response.Write(String.Format("<img src=‘./ShowLocalImage.ashx?path={0}‘ />",
        context.Server.UrlEncode(filePath)));}  }

 ShowLocalImage.ashx

public void ProcessRequest(HttpContext context){context.Response.ContentType = "image/jpeg";String filePath = context.Request["path"];if (filePath != null){if (File.Exists(filePath)){context.Response.WriteFile( filePath );}}}

 

注意:如果要對圖片進行定製(做成縮圖、部分顯示等),則可以在ShowLocalImg.ashx中用Graphic。。

<img>標籤顯示本地路徑的圖片的.NET解決方案

聯繫我們

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