Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Using selected file for image preview

Tags:

angular

As part of our application we would like to preview the files the users are uploading, before they are actually available on the server. To do this I have tried a couple of things:

  • Assigning the file directly to the background-image style attribute. (Both with url() and without)
  • Generating a blob using URL.createObjectURL(), gives WARNING: sanitizing unsafe style value blob:http://localhost:4200/16db9654-3119-4d55-9b59-715c2d31b334 (see http://g.co/ng/security#xss).
    • Adding url() around the blob url: WARNING: sanitizing unsafe style value url(blob:http://localhost:4200/86da46b1-5431-46d0-8757-13c75e09abc2) (see http://g.co/ng/security#xss).
  • Sanitizing the the blob url directly using the DomSanitizer ERROR Error: Required a safe Style, got a URL
    • Adding url() around the sanitized value in the template WARNING: sanitizing unsafe style value url(SafeValue must use [property]=binding: blob:http://localhost:4200/72561f3d-0ff7-435b-8ac9-ec3a7c0cfbb0 (see http://g.co/ng/security#xss)) (see http://g.co/ng/security#xss).
    • Adding url() around the blob url before sanitizing ERROR Error: Required a safe Style, got a URL

And during none of these the background image actually appeared. I checked the dom using the chrome inspecter, and in none of the cases did the attribute actually get set.

So what is the correct way of doing this? I have a File instance at start.

like image 216
Rasmus Hansen Avatar asked Aug 23 '26 22:08

Rasmus Hansen


1 Answers

HTML:

<input type='file' (change)="onAdd($event)">

<div class="col-4 col-sm-4 col-md-4 col-lg-4 col-xl-4" *ngIf="url">
    <img [src]="url">
</div>

Type Script:

onAdd(event: any) {
        console.log(event);
        if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();
            reader.onload = (event: any) => {
                this.slika = event.target.result;
            }
            reader.readAsDataURL(event.target.files[0]);
        }
    }

EDIT:

Change your code to this:

public addFile(event: any) {
    if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();
            reader.onload = (event: any) => {
                this.url = event.target.result;
            }
            reader.readAsDataURL(event.target.files[0]);
        }
  }

and this:

<input type="file" (change)="addFile($event)">

With these changes it should work now.

like image 126
Joe Belladonna Avatar answered Aug 25 '26 13:08

Joe Belladonna



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!