Return image from file system

回眸只為那壹抹淺笑 提交于 2019-12-13 15:27:14

问题


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


回答1:


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");
}



回答2:


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");
}



回答3:


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.



来源:https://stackoverflow.com/questions/39310248/return-image-from-file-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!