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?

1
  • Can you provide some details of your actual error? Commented Jul 29, 2022 at 11:18

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.