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。。

  • 相关阅读:
    不定长内存池之apr_pool
    FFmpeg介绍及参数详细说明
    Linux下ffmpeg安装与开发配置
    基于Live555,ffmpeg的RTSP播放器直播与点播
    ffmpeg开发指南
    boost::bind的使用方法
    开启Linux VNC远程桌面
    Fedora 启动 SSH服务
    Linux中查看进程及杀死进程命令
    __FILE__,__LINE__,FUNCTION__实现代码跟踪调试(linux下c语言编程 )
  • 原文地址:https://www.cnblogs.com/hoosway/p/4264430.html
Copyright © 2011-2022 走看看