Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3: Image loading through controller

I tried using the answer from here, but it did not work. I have the following code:

public ActionResult ShowImage() 
{
    using (FileStream stream = new FileStream(Path.Combine(Server.MapPath("/App_Data/UserUpload/asd.png")), FileMode.Open))
    {
        FileStreamResult result = new FileStreamResult(stream, "image/png");
        result.FileDownloadName = "asd.png";
        return result;
    }

}

When I open up the page I get an error which says: "Cannot access a closed file.". I did some googling on the error, but I only found this error associated with uploading. What causes the issue here?

like image 419
Esa Avatar asked Jun 03 '11 09:06

Esa


1 Answers

Try like this:

public ActionResult ShowImage() 
{
    var file = Server.MapPath("~/App_Data/UserUpload/asd.png");
    return File(file, "image/png", Path.GetFileName(file));
}

or if you want a separate filename:

public ActionResult ShowImage() 
{
    var path = Server.MapPath("~/App_Data/UserUpload");
    var file = "asd.png";
    var fullPath = Path.Combine(path, file);
    return File(fullPath, "image/png", file);
}
like image 66
Darin Dimitrov Avatar answered Sep 20 '22 04:09

Darin Dimitrov