简体   繁体   中英

How to convert an image file into its base64 representation without the leading prefix: “data:image/jpeg;base64” in js&html5

I have below codes in my frontend:

    let reader = new FileReader();
    reader.onload = function(e) {
        _this.imageBase64 = e.target.result;
        alert(_this.imageBase64);
        ...
    }

the alert function shows that the imageBase64 is a base64 string, which is starting with data:image/jpeg;base64 .

The problem is that, is there any elegant way that I can get the base64 string of the image, without this prefix? (I don't want to use substring like function).

Since the server end codes will read this string with the assumption that it only contains the base64 representation of the image.

Maybe base64Str.split(',').pop() is my best choice, as string.slice(start, stop) and string.substring(start, stop) require the exact index.

Seems that we are getting a data url (which has the leading meta data prefix) by using the approach I mentioned. The advantage is that that url can be used directly in some src field. This is the reason why we have that prefix in the front end world.

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