Giorgos Manoltzas
Giorgos Manoltzas

Reputation: 1718

Display image in view from file system

I have an ASP.NET MVC 4 web application which resides in the C:\inetpub\wwwroot\appName directory on the server. I want to store images uploaded by users in D:\appName\UserFolder\ directory and then display these images in a razor view. I have created the following html helper:

public static class MyHtmlHelpers
{
    public static IHtmlString UploadedImage(this HtmlHelper htmlHelper, string url)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var image = new TagBuilder("img");
        image.Attributes["src"] = UrlHelper.GenerateContentUrl(url, htmlHelper.ViewContext.HttpContext);
        return MvcHtmlString.Create(image.ToString(TagRenderMode.SelfClosing));
    }
}

and I use the above helper like this:

@Html.UploadedImage(item.StoreItemImage)

this item.StoreItemImage brings from the database the absolute path of the image (let's say D:\appName\UserFolder\image.jpg). This helper finally renders like this

<img src="D:\appName\UserFolder\image.jpg" />

The image is not displayed in the browser. Also it is not an elegant and safe way to reveal the actual server path where the application stores the images. Any solution please? Thank you.

SOLUTION

So just for the record I post the solution that worked for me according to Cory's suggestion. It may be helpful to others I created the following action method:

public FileResult GetImage(string fileLocation)
    {
        Image image = Image.FromFile(fileLocation);
        byte[] imageArray;

        using (var memoryStream = new MemoryStream())
        {
            image.Save(memoryStream, ImageFormat.Jpeg);
            imageArray = memoryStream.ToArray();
        }

        return File(imageArray, "image/jpeg");
    }

Upvotes: 4

Views: 6199

Answers (1)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107626

Assuming you have some sort of key or ID related to each image in the database, you could instead "hide" the image source by rendering it through an action (using only the database ID to reference it):

public ActionResult GetImage(int dbId)
{
    byte[] image = LoadImageFromDatabase(dbId);
    return File(image, "image/jpeg");
}

And use this markup in your view:

<img src="@Url.Action("GetImage", new { dbId = Model.PhotoDatabaseId })" />

Upvotes: 6

Related Questions