Search code examples
imageasp.net-corewwwroot

How to display images saved in wwwroot in ASP.NET Core projects?


I am working on a multi-project website in ASP.NET Core and Angular.

The first project is just a server side app in Microsoft Visual Studio (back end code, Controllers and link with database) and the second project is a client-side app in Visual Studio Code (Angular, TypeScript code).

So two projects under one umbrella which needs to be an online shop where I have products and some images for every product.

The issue:

I cannot get the images already saved in "wwwroot" folder (in the back end, in my first project in Visual Studio) and display them in the client side (in Angular). I can specify that I have stored images in the "wwwroot" folder (via image name and the image itself) and the image name and image path are saved in the database.

How do I get the images from the backend and display them in the frontend?


Solution

  • The content in the wwwroot should be publicly accessible relative to the base URL of your app. As the documentation explains:

    Static files are accessible via a path relative to the web root. For example, the Web Application project templates contain several folders within the wwwroot folder:

    • wwwroot
      • css
      • js
      • lib

    Consider creating the wwwroot/images folder and adding the wwwroot/images/MyImage.jpg file. The URI format to access a file in the images folder is https:///images/<image_file_name>. For example, https://localhost:5001/images/MyImage.jpg

    So from your Angular app, just use the URLs as expected, like https://localhost:5001/images/MyImage.jpg corresponding to wwwroot/images/MyImage.jpg.