zoukankan      html  css  js  c++  java
  • <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。。

  • 相关阅读:
    Java Web----Java Web的数据库操作(二)
    PHP foreach 遍历数组是打印出相同的数据
    implemented loader.php
    With PHP frameworks, why is the “route” concept used?
    网络包
    长寿之道
    php中print_r 和var_dump 打印变量的区别。
    php 中的全局变量的理解
    php session 严格过期时间实现
    nginx+fastcgi php 使用file_get_contents、curl、fopen读取localhost本站点.php异常的情况
  • 原文地址:https://www.cnblogs.com/hoosway/p/4264430.html
Copyright © 2011-2022 走看看