skip to Main Content

I have this code in my .ts file:

fileUpload(file:UploadedFile){
    var imagesource = `data:${file.Type};base64, ${file.Data}`;
    this.srcPreview = this.sanitizer.bypassSecurityTrustUrl(imagesource);
}

When an image is first uploaded imagesource always evaluates to "data:image/png;base64, undefined". However, if I add a breakpoint before the end of the function and enter data:${file.Type};base64, ${file.Data} into the DevTools console I get "data:image/png;base64, iVBORw0KGgoAAAA...[rest of the data]".

If I then upload another image, the first image appears in the preview. The component is declared as

<img [src]="srcPreview">

Why is ${file.Data} evaluating to undefined at runtime even though debugging it shows the correct value, and why does uploading a second image cause the first image to appear?

2

Answers


  1. Chosen as BEST ANSWER

    Solved by refactoring to correctly listen to the event that was up the call stack of the offending method. The method was executing before a call in uploadEventHandler($event) could complete.


  2. Check Function Call: Ensure that the fileUpload function is being called with the correct parameter. Verify that the file object being passed to the function contains the Type and Data properties.

    Verify Property Existence: Before accessing the Type and Data properties of the file object, check if they exist to avoid errors. You can use optional chaining (?.) or nullish coalescing (??) operators to handle cases where the properties may be undefined or null

    var imagesource = `data:${file?.Type};base64, ${file?.Data}`;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search