I want to convert the string obtained from JavaScript Blob.text() to Blob again and create DataURL.

Asked 1 years ago, Updated 1 years ago, 21 views

Thank you for your cooperation.
Basically, it is as the title says.

In detail,
I would like to receive a zip file on my browser, unzip it on JS, save the image data inside to localStorage, and use it by transitioning to the next screen.It has a purpose such as .
The important thing is that we want to complete the image data once in a side dish client such as a server.
So, even if it's not the answer to your question, if there's something like this that you can do without using localStorage, we'll be waiting for you to do that.

What I tried is

//blob contains image data.

const str = wait blob.text();

constreBlob = new Blob([str], {type: 'image/png'});

const fileReader = new FileReader();
fileReader.readAsDataURL(reBlob);
fileReader.onload=()=>{
    document.getElementById('imageElement').src=this.result;
}

I tried writing the code, but the returned dataUrl seems to be incorrect, and I see an icon that appears when the image with the img tag does not exist.

I wonder if writing like this won't work.

I've looked at some sites, but I couldn't find anyone like me in a situation, so I'd like to ask you a question.

javascript

2022-09-30 15:58

1 Answers

Self-resolved.

I was converting to str once because of the complexity of the code when I put asynchronous processing using FileReader, but I was able to solve this problem by creating my own FileReader class that inherited FileReader.

export class MyFileReader extensions FileReader{
    constructor(){
        super();
    }

    public readAsDataURL (blob:Blob): Promise <string | ArrayBuffer | null > {
        return this.readAs(blob, 'readAsDataURL');
    }

    private readAs (blob:Blob, callback:string): Promise <string | ArrayBuffer | null > {
        return new Promise ((resolve, reject) = > {
            super.addEventListener('load',({target})=>{
                resolve(target!.result);
            });
            super.addEventListener('error',({target})=>{
                reject(target!.error);
            });
            // @ts-ignore
            super [callback] (blob);
        });
    }
}

const str = wait new MyFileReader().readAsDataURL(blob)as string;

document.getElementById('imageElement').src=str;


2022-09-30 15:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.