1
votes

Getting unsafe URL error in console while displaying an image in Angular 6

Here i am taking the image

<br>Primary Image <input type="file" (change)="readUrl($event)">

In the other component, I want my image to be shown

<tr *ngFor="let x of response">
    <td>
        <img [src]="x.productPrimaryImage">
    </td>
</tr>

Method to get the path of the image.

readUrl(event) {
    this.productPrimaryImage = event.target.value;
}

WARNING: sanitizing unsafe URL value C:\Users\mayursinghal\Pictures\Screenshot (9).png (see http://g.co/ng/security#xss)

2

2 Answers

6
votes

This is a warning given by Angular because your application can be exposed to XSS attacks. If you want to bypass this security warning, you need to first sanitize the URL to make it safe to display it in the UI. You can do this using the DomSanitizer (Source: docs).

Create a function to sanitize the image url in your component

import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

...

constructor(private sanitizer: DomSanitizer) { }

sanitizeImageUrl(imageUrl: string): SafeUrl {
    return this.sanitizer.bypassSecurityTrustUrl(imageUrl);
}

Then in your template, call this function to sanitize your URL.

<tr *ngFor="let x of response">
    <td>
        <img [src]="sanitizeImageUrl(x.productPrimaryImage)" />
    </td>
</tr>

WARNING: calling bypassSecurityTrustUrl with untrusted image URLs exposes your application to XSS security risks!

-1
votes

First, you are providing absolute path which will simply stop working after deployment. Move your images inside project and use relative urls like /images/Screenshot (9).png

Secondly, youse [src] instead

<img [src] = "x.productPrimaryImage">