Iancu Nelutu
Iancu Nelutu

Reputation: 93

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?

Upvotes: 9

Views: 17330

Answers (4)

Silvan
Silvan

Reputation: 369

In addition to the accepted answer you need to configure your ApplicationBuilder (Configure this method in Startup.cs):

app.UseStaticFiles();

Without this your wwwroot folder will not get served. You can also configure UseStaticFiles() with 'StaticFileOptions' to serve a different folder than wwwroot.

Upvotes: 6

CaptainGenesisX
CaptainGenesisX

Reputation: 405

I had the same issue and I tried 20 different things until I finally found a solution. Here is what you need to do:

  1. Create an images folder inside the wwwroot folder, if you have not already done so.
  2. Put the image file into the newly created images folder.
  3. In the img tag, enter the file path to the image in the following example format:
<img src="~/images/mcd-logo.jpg" title="McDonald's Logo" alt="McDonald's Logo" />

The big differences for me was putting the images folder in the wwwroot folder and then adding the ~ to the path.

Upvotes: 3

Eliseo
Eliseo

Reputation: 57971

An angular .html

<img [src]="img"/>

Need that

img="myimage.jpg"        //if wwwroot/myimage.jpg
img="images/myimage.jpg" //if wwwroot/images/myimage.jpg

See that there are not a slash at first.

Upvotes: 4

Noah Stahl
Noah Stahl

Reputation: 7613

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.

Upvotes: 7

Related Questions