2

I'm trying to make a preview of some image file that I get from the input, example file looks like this:

enter image description here

So I found out that to show preview of file first of all I have to change this file to Blob, I was looking for solution and I found something like this:

  private imageFileToBlob(imageFile) {
    const splitedData = imageFile.image.split(',');
    const mime = splitedData[0].match(/:(.*?);/)[1];
    const bstr = atob(splitedData[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type: mime});
  }

But I don't know how to edit this to make it fit to my type of input file. Can someone help/explain how it should be resolved?

I believe when I get Blob file then I can put it directly into <img [src]='blobHere'>?

Thanks!

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Dominik Z
  • 161
  • 4
  • 14
  • Have you considered using [URL.createObjectURL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) instead of a blob? I assume that you are wanting to show a preview of the image while you are uploading it to a backend, right? – kyle Apr 14 '20 at 16:13
  • Each [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) is already an instance of `Blob`. You can pass a `File` directly to `URL.createObjectURL()`, which gives you a short URI that you can use as an image `src`. – Patrick Roberts Apr 14 '20 at 16:18
  • Ok so I tried to use `createObjectUrl()` and I got `unsafe:blob:http://localhost:4202/3e4b33a3-f7fd-4690-920b-a3e89625fda3 net::ERR_UNKNOWN_URL_SCHEME` error. – Dominik Z Apr 14 '20 at 16:47

2 Answers2

0

As API said, the File is already a Blob. You can simply use:

let myFile: File = ...; // here is your file
myObject.content = myFile;
// here, "content" is typed by "Blob"
Elikill58
  • 4,050
  • 24
  • 23
  • 45
-2

Try this:

private imageFileToBlob(imageFile) {
    const url = URL.createObjectURL(imageFile);
    return fetch(url).then(res => res.blob())
}

You will get a Promise with a Blob

Reynier Rivero
  • 2,042
  • 2
  • 8
  • 12