简体   繁体   English

如何将图像文件转换为不带前缀的base64表示形式:js&html5中的“ data:image / jpeg; base64”

[英]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 . alert功能显示imageBase64是base64字符串,以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? 问题是,有没有任何优雅的方法可以在没有此前缀的情况下获取图像的base64字符串? (I don't want to use substring like function). (我不想使用substring类的功能)。

Since the server end codes will read this string with the assumption that it only contains the base64 representation of the image. 由于服务器端代码将假设仅包含图像的base64表示形式读取此字符串

Maybe base64Str.split(',').pop() is my best choice, as string.slice(start, stop) and string.substring(start, stop) require the exact index. 也许base64Str.split(',').pop()是我最好的选择,因为string.slice(start, stop)string.substring(start, stop)需要精确的索引。

Seems that we are getting a data url (which has the leading meta data prefix) by using the approach I mentioned. 似乎我们通过使用我提到的方法获得了data url (具有领先的meta数据前缀)。 The advantage is that that url can be used directly in some src field. 优点是可以直接在某些src字段中使用url。 This is the reason why we have that prefix in the front end world. 这就是为什么我们在前端世界中具有该前缀的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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