Reputation: 1583
Is there any way to display image in an asp.net core 2 (razor) web application from local drive ?
The reason I want do to this is that I'm developing a game server which contains a game server and two websites (front end and an admin panel) and all of those will require access to the mentioned images which in this case is profile images and that's why I didn't put those images in the wwwroot folder.
Sample image address: "C:\game_data\avatars\default.png"
Upvotes: 3
Views: 12239
Reputation: 1
Add below code in startup class and instead of images, set your folder:
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "images")),
RequestPath = "/images"
});
Upvotes: 0
Reputation: 131730
In most cases, the most secure (and easiest) optin is to store images under the site's root folder to avoid giving the web site's account access outside the site folder itself.
User profile images aren't static though. That's why they're often stored in a database or other storage.
You can map a specific request path to a custom location in UseStaticFiles. From the documentation example :
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles(); // For the wwwroot folder
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")),
RequestPath = "/StaticFiles"
});
}
The first call configures wwwroot
as the root for static files. The second call overrides this for requests starting with /StaticFiles
and points to a folder called MyStaticFiles
under the application's folder.
You could expose all profile pictures under the avatar
path with this code:
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles(); // For the wwwroot folder
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
"X:\game_data\avatars\"),
RequestPath = "/avatars"
});
}
A better option would be to load the location from a configuration file.
Another consideration is that simply mapping the folder to a path will allow anyone to read profile pictures if they can guess their name. This may or may not be a concern.
If it is, you use a controller that only returns the current user's as a FileResult, eg:
class AvatarsController
{
[HttpGet]
public async Task<IActionResult> Get()
{
var userID=SomehowFindTheCurrentUserID();
var avatarPath= Path.Combine(_avatarRoot,$"{userID}.jpeg");
return File(avatarPath, "image/jpeg");
}
}
Upvotes: 10