How to obtain image from server directory and display in Angular 14


So I have a web Api method that for the moment has a hard coded value in (will go to service eventually) but for now I’m just trying to prove the concept.

We have a bunch of images held on disk and not in a DB. I need to render images from this directory onto an Angular 14 page.

For my test From the web Api I have the following method:

public List<Photos> GetPhotos()
    return new List<Photos>() { new Photos { id = 1, cost=10.2d, photographer = "bill", title="photo 1", url = "C:/photos/img20230110_21490374.jpg" } };

this is returned to Angular in an object.

in my Angular App, I have the following declared:

  name: 'safeUrl'
export class SafeUrlPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }
  transform(url: string) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);

then I use it in my page using

 <img src="{{ photo.url | safeUrl }}" />

My photo object in Angular is declared as:

export interface Photo {   
 id: number;   
 title: string;   
 cost: number;   
 url: string;   
 photographer: string; }

The image does not display, in the console, I receive an error:

unsafe:SafeValue must use [property]=binding:
C:/photos/img20230110_21490374.jpg (see
GET unsafe:SafeValue must use [property]=binding: C:/photos/img20230110_21490374.jpg (see

Can anyone point me in the right direction to get this working.

>Solution :

You are using absolute file path as URL, it will not work. Also you are using files that are outside of wwwroot directory, which also will not work.

The first step is to copy photos directory to wwwroot.

Then you have to build URLs like this:

    // replace "http://localhost:5001" with value from config, or from Request URL, or hardcode
    var baseUrl = new Uri("http://localhost:5001", UriKind.Absolute);

    var result = new Uri(baseUrl, "photos/img20230110_21490374.jpg").ToString();

Leave a Reply Cancel reply