简体   繁体   中英

How to create a base64-encoded string from a local file image in javascript

I have been trying to convert an image file from my local machine but it seems not working for me. I don't want to upload the image using an input because I'm only having the image path in production and i want to store the base64 string. but if there is a better way i can handle this then i don't mind


        const reader = new FileReader();
         const file = new File([imgUrl], { type: "image/png" });
        console.log(file);
        reader.addEventListener("load", function (e) {
            console.log(e.currentTarget.result);
        }, false);

        const data = reader.readAsDataURL(file);
        return data;
        }
        const img = "localhost:8080/start app abnner.png"; // my image path
        getDataUrl(img);

The key is to use the result property of your object (seeFileReader API. )

const reader = new FileReader()
reader.readAsDataURL(image) // assuming "image" is your file
reader.result // here is your base64 string

So in your case, it should be:

const data = reader.readAsDataURL(file);
return data.result;

I had to do something like this once, so I made a little plugin if you want: encode-image-uri . It has the advantage of using promises, so you're 100% sure that you're calling any function only when the conversion is done and your data is ready.

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