標籤:
今天朋友問了我一個奇怪的需求:項目中要求圖片上傳到工作目錄,上傳後要在網頁中通過<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解決方案