Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 305
user3272018 Avatar asked Oct 27 '25 07:10

user3272018


2 Answers

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");
}
like image 130
Tseng Avatar answered Oct 29 '25 23:10

Tseng


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");
}
like image 21
Shyju Avatar answered Oct 29 '25 22:10

Shyju



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!