0

I'm having this sanitize URL error in Angular, I've seen many solutions, but I've not been able to use them in my scenario, that's why I'm asking the question.

Here is my function:

@Input()
    maxFileSize: number = 1000000;

    public fileChangeEvent(fileInput: any) {
        if (fileInput.target.files && fileInput.target.files[0]) {
            const reader = new FileReader();
            reader.onload = (e: any) => {
                if (e.target.result) {
                    if (e.target.result.length < this.maxFileSize) {
                        this.value = e.target.result;
                    } else {
                        alert(`Logo size ${e.target.result.length} cannot exceed ${this.maxFileSize} bytes.`);
                    }
                }
            };

            reader.readAsDataURL(fileInput.target.files[0]);
        }
    }

I've tried this.sanitizer.bypassSecurityTrustUrl(url), but in my case, fileInput.target.files[0] is a blob, so I always get an error when wrapping it worth the sanitizer function.

I'm using it in the view like this:

 <ng-container *ngIf="value">
        <div class="input-group-append">
            <div class="img-thumbnail">
                <img src="{{value}}" alt="Preview" />
            </div>
            <button class="btn btn-danger btn-lg" type="button" (click)="clearLogo()">
            <i class="fa fa-trash" aria-hidden="true"></i>
            Delete
            </button>
        </div>
    </ng-container>
enter code here

I've also tried [src]="{{value}}", but that did not work as well.

I'm getting this error:

WARNING: sanitizing unsafe URL value

Please where am I getting it wrong?

Eng_Farghly
  • 1,987
  • 1
  • 23
  • 34
Code Haven
  • 51
  • 6

1 Answers1

0

I hope this fixes your issue.

constructor(private sanitizer:DomSanitizer){...}
    ....
    
          let file = event.target.files[0];
          let blob = new Blob([file], { type: file.type });
          let url = window.URL.createObjectURL(blob);
    
          this.value = this.sanitizer.bypassSecurityTrustUrl(url);