ASP.NET Core static files outside wwwroot folder loading issue

49 views Asked by At

I am working on an ASP.NET Core web application and I have user profile upload and display functionality. I am saving the file in a different folder which is outside of the wwwroot folder. I have added to include the outside folder as static files options in programs.cs but I'm still unable to display the image.

Here's my code:

program.cs:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider("S:\\FileRepo")
});
app.UseStaticFiles();

ImagePath in model:

S:\FileRepo\Upload\dc41a1b0-28ee-4910-8010-f728c09c2c78_profilePhoto.jpg

And I have used an <img> tag in my view page to display the image

<img src="S:\FileRepo\Upload\dc41a1b0-28ee-4910-8010-f728c09c2c78_profilePhoto.jpg" alt="Profile Photo">

The app is unable to load the image and I am getting this error:

Not allowed to load local resource: file:///S:/FileRepo/Upload/dc41a1b0-28ee-4910-8010-f728c09c2c78_profilePhoto.jpg

Can you please help me figure out what I am missing?

I tried with static files options. But it still is throwing that error. Is it possible to suggest any other approach or correct the above logic?

1

There are 1 answers

0
Yuning Duan On

If you do not configure RequestPath, the client will directly use the relative path of the file when requesting a static file. You can use <img src="/Your image.png" alt="Profile Photo"> directly,Or You can also use RequestPath to configure the request path for static files.

Here is an example you can use as a reference:

This is the path where I store an outside image:

enter image description here

Program.cs:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(@"C:\FileRepo\Upload"),
});

Page:

<img src="/IMAGE2.png" alt="Profile Photo">

Result: enter image description here You can also configure the request path of static files :

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(@"C:\FileRepo\Upload"),
    RequestPath = new PathString("/MyPath")
});

Page:

<img src="/MyPath/IMAGE2.png" alt="Profile Photo">