今天朋友问了我一个奇怪的需求:项目中要求图片上传到工作目录,上传后要在网页中通过<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。。