Junior Mayhe
Junior Mayhe

Reputation: 16411

How to avoid file:// protocol and show images using http://

It seems we cannot show images on Google Chrome using file:// protocol.

I think would be nice to have a way to load the file on a remote network such as file://my-network-computer/my-folder/my-file.jpg and render it as image on a asp.net page.

Is it possible to load bytes from a file on a network drive, then render its content as image on asp.net page?

Upvotes: 1

Views: 2567

Answers (2)

Michiel van Oosterhout
Michiel van Oosterhout

Reputation: 23084

You could write a handler that opens the file on the network using its UNC path and writes its contents to the response using 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; } }
}

Then you set the image src to the handler url:

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

Be very strict about checking the input, don't create a handler that would allow someone to open just any file on your network. Restrict access to a single folder, only give the worker process access to that folder and check for valid file extensions (e.g. jpg, jpeg, png, gif).

This is a rather simple example, don't use it in production without testing.

For alternative ways to write content to the response, and more example code, see:

Upvotes: 3

Icarus
Icarus

Reputation: 63966

Yes, it's possible.

You can transform the bytes to a base64 string and set the image src to be the base64 string.

Example:

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

And the way you convert the bytes to a base64 string is:

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

Upvotes: 2

Related Questions