How to recreate a File object from a .png file by reading and saving its contents?

Viewed 29

In my angular application, a user selects an image from their local machine to display in an image element on my component. If the user loads another route, and then returns to the page, I would like the image to be visible without the user having to re-select it.

From other threads, it appears that the only way to do this is to save the contents of the file elsewhere, since the temporary file that is created is deleted when the route changes.

I try to do that by saving the file contents in a model object maintained by a service in my application, an image element on the page displays a broken link to create a new source URL from the reconstituted file object.

Here's the code I originally use to save the contents of the file selected by the user in the input element:

public async setImage(evt: Event) {  
  let localFile : File;
  let target: HTMLInputElement = evt.target as HTMLInputElement;
  localFile = target.files[0];
  this.model.fileName = localFile.name;
  let reader = new FileReader()
  let self = this;
  //read the file and save the result in the model      
  reader.onload = function(progEvt : ProgressEvent) { 
     self.model.localImageFile = render.result;
  }
  reader.readAsDataURL(localFile);
  //generate the url to display in the image element:
  let url = URL.createObjectURL(localFile);
  this.previewImageUrl = this.sanitizer.bypassSecurityTrustUrl(url);
}

This works as expected and displays the image selected by the user.

When the user returns to the page, we recreate the file and attempt to use as the source for the image element:

reloadImage() {
  let base64 = this.model.localImageFile;
  let fileName = this.model.filename;
  let parts = base64.split(',');
  let content = parts[1];
  let filetype = base64[0].split(";")[1];
  let blob = new Blob([content], { type: filetype });
  let file = new File([blob], fileName, { type: filetype });
  let url=URL.createObjectURL(file);
  this.previewImageUrl=this.sanitizer.bypassSecurityTrustUrl(url);
}

By logging both the content and filetype to the console, it looks like the original PNG file data was successfully retrieved, and the element has its source property set to "previewImageUrl", but nevertheless, the image doesn't appear. The element displays similar to a broken link. I assume this means I have failed to reconstruct the file correctly, but I’m not sure where I've gone wrong.

Suggestions appreciated!

0 Answers
Related