Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting unsafe URL error while displaying image

Tags:

angular

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)

like image 498
mayur singhal Avatar asked Sep 06 '26 05:09

mayur singhal


1 Answers

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!

like image 74
nash11 Avatar answered Sep 07 '26 19:09

nash11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!