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:
[HttpGet]
[Route("getPhotos")]
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:
@Pipe({
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 https://g.co/ng/security#xss):1 GET unsafe:SafeValue must use [property]=binding: C:/photos/img20230110_21490374.jpg (see https://g.co/ng/security net::ERR_UNKNOWN_URL_SCHEME
Can anyone point me in the right direction to get this working.
CodePudding user response:
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();