Thorin Oakenshield
Thorin Oakenshield

Reputation: 14662

How to display images from local disk in mvc4?

In my MVC(4) application, I'm fetching the image files from the local directory and displaying it in the browser.

I've a model to store the details,and a controller to get the files and a view to display them.

Model

public class ImageModel
{
    List<string> _images = new List<string>();

    public ImageModel()
    {
        _images = new List<string>();
    }

    public List<string> Images
    {
        get { return _images; }
        set { _images = value; }
    }
}

Controller

public ActionResult Index()
{
    var imageFiles = new ImageModel();
    imageFiles.Images.AddRange(Directory.GetFiles(@"c:\mypath"));
    return View(imageFiles);
}

View

@for (int imgIndex = 0; imgIndex < Model.Images.Count; imgIndex++)
{
    <div >
      <img src = @Model.Images[imgIndex] alt="Image"  />
    </div>
}

But I can not view the images in the browser, its showing empty boxes with alt.

What did I miss here? Should I create a virtual directory instead of physical location.

Upvotes: 1

Views: 5429

Answers (3)

Igarioshka
Igarioshka

Reputation: 677

looking at the code snippet, it seems to me that you forgot to surround the path with quotes

<img src = "@Model.Images[imgIndex]" alt="Image"  />

but looking at the overall code, i would recommend to use relative paths.

UPD: For a more detailed explanation, i would recomentd this blog post

Upvotes: 0

e_c
e_c

Reputation: 1

The problem is your path names. This might help:

Controller:

public ActionResult Index()
{
        var imageFiles = new ImageModel();
        imageFiles.Images.AddRange(System.IO.Directory.GetFiles(@"C:\wherever\files\are\"));
        for (int i = 0; i < imageFiles.Images.Count; i++)
        {
            // get rid of the fully qualified path name
            imageFiles.Images[i] = imageFiles.Images[i].Replace(@"C:\wherever\files\are\", "");
            // change the slashes for web
            imageFiles.Images[i] = imageFiles.Images[i].Replace('\\','/');
        }
        return View(imageFiles);
}

View:

@for (int imgIndex = 0; imgIndex < Model.Images.Count; imgIndex++)
{
    <div >
      <img src = "@Model.Images[imgIndex]" /> <!-- put the file in quotes -->
    </div>
}

Upvotes: 0

devio
devio

Reputation: 37205

First, local files require the file:// URI scheme. You seem to use the native file path as img src.

But the browser security model forbids the use of local source from inside a page served by a web server (http://, https:// protocols).

To fix your situation, the implement a controller that take the desired image file name as parameter, and serve its content using the File() action.

Upvotes: 2

Related Questions