【问题标题】:How to avoid file:// protocol and show images using http://如何避免使用 file:// 协议并使用 http:// 显示图像
【发布时间】:2012-02-03 12:03:24
【问题描述】:

我们似乎无法使用 file:// protocol 在 Google Chrome 上显示图像。

我认为有一种方法可以将文件加载到远程网络(例如 file://my-network-computer/my-folder/my-file.jpg)并将其呈现为 asp.net 页面上的图像。

是否可以从网络驱动器上的文件加载字节,然后在 asp.net 页面上将其内容呈现为图像?

【问题讨论】:

  • 只是为了澄清:不仅仅是chrome不会这样做;所有值得一试的浏览器都应该停止它。

标签: c# asp.net google-chrome http-protocols file-uri


【解决方案1】:

您可以编写一个处理程序,使用其 UNC 路径在网络上打开文件,并使用 Response.WriteFile 将其内容写入响应:

<%@ WebHandler Language="C#" Class="Handler" %>

using System.IO;

public class NetworkImageHandler : System.Web.IHttpHandler
{
  // Folder where all images are stored, process must have read access
  private const string NETWORK_SHARE = @"\\computer\share\";

  public void ProcessRequest(HttpContext context)
  {
      string fileName = context.Request.QueryString["file"];
      // Check for null or empty fileName
      // Check that this is only a file name, and not 
      // something like "../../accounting/budget.xlsx"
      // Check that the file extension is valid

      string path = Path.Combine(NETWORK_SHARE, fileName);
      // Check if the file exists

      context.Response.ContentType = "image/jpg";
      context.Response.WriteFile(path, true);
  }

  public bool IsReusable { get { return false; } }
}

然后将图像src 设置为处理程序url:

<asp:Image runat="server" ImageUrl="~/NetworkImageHandler.ashx?file=file.jpg" />

检查输入时要非常严格,不要创建允许他人打开您网络上的任何文件的处理程序。限制对单个文件夹的访问,只允许工作进程访问该文件夹并检查有效的文件扩展名(例如 jpg、jpeg、png、gif)。

这是一个相当简单的例子,不要在没有测试的情况下在生产中使用它。

有关将内容写入响应的替代方法以及更多示例代码,请参阅:

【讨论】:

    【解决方案2】:

    是的,这是可能的。

    您可以将字节转换为base64字符串并将图像src设置为base64字符串。

    例子:

    <img src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////
    wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4ML
    wWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="
    alt="Base64 encoded image" width="150" height="150"/>
    

    您将字节转换为 base64 字符串的方式是:

     base64String = System.Convert.ToBase64String(binaryData, 
                                0,
                                binaryData.Length);
    

    【讨论】:

    • 这是否适用于较大的图像。在几 kB 之后,您没有达到 url 长度限制吗?
    • @CodeInChaos 确实有一些限制,这篇维基百科文章(en.wikipedia.org/wiki/Data_URI_scheme)有非常透彻的解释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多