简体   繁体   中英

Practical way to handle many base64-encoded images in javascript (client-side)?

I'm building aa website which allows a user to download a personalized pdf. I'm trying to use a javascript library for pdf generation, either jspdf or pdfkit . Neither library can use paths to include images in the browser. They need a base64-encoded data URI. Bummer, I have to include many images. These images are stored on the server.

I'm looking for a way to deal with this. I was thinking of batch encoding all my images, and storing the corresponding strings in a json file, which I would then read from when I need to insert an image. I can't do this manually because even a single string chokes my editor. I also can't store the encoded strings in a database, as I have none.

I understand this question isn't very precisely framed. Suggestions to improve it are welcome.

There are several ways to do this, the most straightforward way I can think of would be to create a base64 string from the onchange event of a file input, and pass the file to the onload event of the HTML Filereader api.

html

<input type="file" onchange="selectFile(this.value)">

javascript

selectFile(event: Event | any) {
    if (event.target.files && event.target.files[0]) {
        const reader = new FileReader();

        reader.onload = (event: ProgressEvent) => {
            this.file = event.target.result;
        }
        reader.readAsDataURL(event.target.files[0]);
    }
}

Then you would pass this.file to your api, or call your api directly from reader.onload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM