开发者

Loading an image control from a local drive

I ha开发者_JS百科ve a folder C:\Images which has a some images. This folder is not inside my project and I would to know if there is a way to load an image from that folder on to an ASP.NET Image control.

<asp:Image ID="img" runat="server" />

One solution could be to make the Images folder a Virtual directory on the IIS but I would like to know if this can be done without creating a virtual directory for the Images folder.


Assuming proper access is granted to the Images folder you could do something like this:

Your main page:

protected void Page_Load(object sender, EventArgs e)
{
    mainImage.ImageUrl = "ImageHandler.ashx?image=MyImage.jpg";
}

ImageHandler:

public void ProcessRequest(HttpContext context)
{
    byte[] imageBytes = File.ReadAllBytes(@"C:\Images" + context.Request["image"]);
    context.Response.ContentType = "image/jpeg";
    context.Response.BinaryWrite(imageBytes);
}


At the end of the day, the image needs to be sitting somewhere that the user's browser can see it.

That means your options are:

  • Move the image to a directory on the webserver
  • Set the image's directory up as a Virtual Directory
  • Copy the image at runtime to a directory on the webserver

The Best Practice answer is to put the images into your project if they're part of the site, or to map a Virtual Directory if the directory is a store of user-uploaded images.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜