user3272018
user3272018

Reputation: 2419

Return image from file system

There is successfully uploaded image in file system and I want to get access to it. So, I have written GET-method

[HttpGet]
public ActionResult Get(string id) {
    var path = $@"d:\smth\upload\{id}.jpeg";
    return File(path, "image/jpeg");
}

I'm totally sure that there is the file in required path with required name, but anytime a try to create File(path, "image/jpeg") I get Could no find file exception. Seems like i dont have access to folders outside wwwroot. Maybe I have missed something important from working with static file article?

So, could anyone explain how to return image that stored in file system outside web-server folder via GET-method

Upvotes: 4

Views: 5191

Answers (3)

Shyju
Shyju

Reputation: 218722

The File method does not have an overload which takes a physical location. There is one which takes a virtual path, for which your image should be under web app root.

But there is another overload which you can use for your usecase. This one take a byte array as the first argument of File method. You can read the file from accessible physical directory (assuming your file exists) and convert it to a byte array and pass it to the File method.

[HttpGet]
public ActionResult Get(string id)
{
   var path = $@"d:\smth\upload\{id}.jpeg";
   byte[] bytes = System.IO.File.ReadAllBytes(path);
   return File(bytes, "image/jpeg");
}

Upvotes: 3

Tseng
Tseng

Reputation: 64141

While what @Shyju says is true and that the File helper method doesn't accept a physical file path, PhysicalFile helper method does (see GitHub source).

[HttpGet]
public ActionResult Get(string id) {
    var path = $@"d:\smth\upload\{id}.jpeg";
    return PhysicalFile(path, "image/jpeg");
}

Upvotes: 8

Saskia
Saskia

Reputation: 524

You can't, if you could, that would mean everybody in the outside world could make a GET/POST form and access your files outside the public folder. If somebody uploads a file to your webserver, it should reside in your tmp directory, which you should be able to access with asp.

Upvotes: -2

Related Questions