7

I stored Images In a folder name "Images" which is not in wwwroot folder. So now i am unable to access it so my question is that How to give access to folder which contain images and thats folder is not the sub-folder of wwwroot? Or Its compulsory to put these files in wwwroot folder?

Ahmad Qasim
  • 452
  • 1
  • 8
  • 26

1 Answers1

12

Yep Asp.Net Core provides a way to do that. You can serve images from an Images directory which is not in the wwwroot folder. In fact, you can serve them from anywhere including embed resource files or even out of a database.

The key is to register a FileProvider in the Configure method of the Startup.cs file so that Asp.Net Core knows how to access the file to be served.

So for example, in your case since you want to serve images from a directory called Images, let's say your directory hierarchy looks like this:

wwwroot
     css
     images
     ...

 Images
     my-image.png

To serve up my-image.png from Images you could use the following code:

 public void Configure(IApplicationBuilder app){
     app.UseStaticFiles(); // For the wwwroot folder

     app.UseStaticFiles(new StaticFileOptions(){
     FileProvider = new PhysicalFileProvider(
         Path.Combine(Directory.GetCurrentDirectory(), @"Images")),
         RequestPath = new PathString("/Images")
     });
 }

You can learn more about serving static files here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files

RonC
  • 31,330
  • 19
  • 94
  • 139
  • Is there a way to serve from another URL ? As an example: What if I want to serve images from www.google.com/images as www.myapp/admin/images ? – Shezi Nov 08 '22 at 23:09
  • 1
    This should be asked as a separate question. But in general if you own the other domain and have it pointing to the same server, then you could serve whatever you want to it including images from any location you have access to. – RonC Nov 09 '22 at 15:21
  • Just created a new question. Your help will be appreciated please. https://stackoverflow.com/q/74378891/746208 – Shezi Nov 09 '22 at 17:20