skip to Main Content

I’m trying to serve images from a directory outside of the current ASP.NET Core 6 project that I’m working with and none of the images are showing. I’ve read the Docs and some of the other SO posts. So I kinda understand what needs to happen, I just don’t know if I’m doing this right.

Program.cs

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
  FileProvider = new PhysicalFileProvider(Path.GetFullPath("C:\Development\Website\Classic\websiteImages\Images\ItemImages")),     
});

in the View I call the image like so

 <img src="@Url.Content(@pic.FileLocation +"\"+ @pic.FileName)" />

and I’ve tried it this way as well

 <img src="@[email protected]" alt="@pic.FileName" width="100" class="img-thumbnail d-inline">

This is the @pic.FileLocation path: "C:DevelopmentWebsiteClassicwebsiteImagesImagesItemImages"

and @pic.FileName is something coming from the Database like 10001234.jpg

If I copy and past the image path into a browser tab it shows the image, so I know the image is there.

Here is what the src looks like in the browser.

enter image description here

3

Answers


  1. What do you get for the img’s src attribute after the @Url.Content() call? That is, what address is actually rendered to the browser as part of the final html?

    If the address still starts with C:Development, something isn’t right. The address in the image element’s src attribute resolves from the perspective of the user’s browser, not your web server, so it needs to look something more like this:

    https://example.com/classic-site/websiteImages/Images/ItemImages/10001234.jpg
    

    Then in your application, if the the classic site is no longer online on it’s own you need to able to receive a request for that address and map to the right place so it serves the right file.

    You have to be careful testing this, because very often during development the server and browser run on the same computer. In that scenario, an address like C:DevelopmentWebsite... might seem to work just fine in the web browser, but it will fail as soon as you start hosting the application on it’s own server, away from the end user’s browser.

    Login or Signup to reply.
  2. Since you’ve already configured the statifiles middleware to provide files from that specific folder, this should work:

     <img src="~/10001234.jpg" />
    

    So as long as you generate URLs in this form: ~/{fileName} you should be good.

    Here is the main documentation on serving files outside of the project folder structure:

    Login or Signup to reply.
  3. Just remove app.UseStaticFiles(); because you have already app.UseStaticFiles(new StaticFileOptions() ... and then Try this:-

    <img src="~/@pic.FileName" alt="@pic.FileName" width="100" class="img-thumbnail d-inline">
    

    Hope it will resolve your issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search