<img>标签显示本地路径的图片的.NET解决方案

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

转载于:https://www.cnblogs.com/hoosway/p/4264430.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值