1

I am using the ngx-image-cropper, https://www.npmjs.com/package/ngx-image-cropper, and need to programmatically set the default loaded image. The cropper provides an outlet to do so through the imageFileChanged API input. It requires a File type and any image I've attempted to pull in has been in Blob format.

Is there a way to convert a Blob to a File?

I haven't found any specific examples of someone doing this with this particular image cropper. I am open to using another one if this functionality is included and it's well supported.

I can successfully get a Blob image from our own server or a random api, I just haven't found a way to convert that to a File.

Is there an alternative to the HttpClientModule that would produce a different type?

The image cropper in its basic usage takes in an file and uses that in the cropping tool. Is there a way to do this programmatically?

I'm happy to provide any code, I just don't know what would help in this case.

William H.
  • 93
  • 2
  • 12

2 Answers2

4

Convert Only

let file = new File([blob], "name.extension");

If you are trying to download a blob and convert it to any file type, you do something like this. Since you said you are downloading and pulling an image.

Fetch Convert, Download, Extension

function download(url, filename) {
    // Request
    fetch(url, { 
        mode: 'no-cors' /*{mode:'cors'}*/
    // Callback
    }).then((transfer) => {
        // Return blob
        return transfer.blob();
    // Return data
    }).then((bytes) => {
        // Create an element
        let elm = document.createElement('a');
        // Add blob data to element
        elm.href = URL.createObjectURL(bytes);
        // Download blob data with certain extension
        elm.setAttribute('download', filename);
        elm.click()
    }).catch((error) => {
        console.log(error);
    })
}

download('http://BLOB', 'EXTENSION');

I think this is the convert function your looking for How to convert Blob to File in JavaScript

Typescript:

public convert = (blb: Blob, f:string): File => {
    var b: any = blb;
    b.lastModifiedDate = new Date();
    b.name = f;
    return <File>theBlob;
}
    const Data = new Blob();
    let file = Convert(Data, 'extension');
ABC
  • 2,068
  • 1
  • 10
  • 21
0

Turns out, this is a duplicate. This will help you out. Thanks to @Raymond for pointing me to that article.

William H.
  • 93
  • 2
  • 12