如何从 Javascript FileReader base64字符串中剥离类型?

我的 Javascript 中有以下代码:

var reader = new FileReader();
reader.onloadend = function () {
alert(reader.result);
};

这里显示了以下数据:

 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAAAAABX3VL4AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gYSDCUgSze0AAAAAA5JREFUCNdjrGJgYmAAAAJ0AH4SDHVIAAAAAElFTkSuQmCC

问题是我只想要逗号后面的部分。我试着从 reader.result.valuereader.result.valueOf()和其他一些组合中得到它,但是找不到正确的组合,只能得到从逗号后面开始的 base64字符串。第二个想法是简单地去掉逗号和之前的所有内容,但我不知道该怎么做。

有人知道怎么做吗? 欢迎提供任何建议!

83628 次浏览

The following functions will achieve your desired result:

var base64result = reader.result.split(',')[1];

This splits the string into an array of strings with the first item (index 0) containing data:image/png;base64 and the second item (index 1) containing the base64 encoded data.

Another solution is to find the index of the comma and then simply cut off everything before and including the comma:

var base64result = reader.result.substr(reader.result.indexOf(',') + 1);

See JSFiddle.

let reader: FileReader = new FileReader();
 

reader.onloaded = (e) => {
let base64String = reader.result.split(',').pop();
};

or

let base64String = /,(.+)/.exec(reader.result)[1];

You can try splitting your data using ;base64,.

// In here you are getting the data type. Ex - png, jpg, jpeg, etc. You can use this for any further purposes.
var dataType = reader.result.split(';base64,')[0];


// In here you are getting the base64 string and you can use this for your purpose.
var base64result = reader.result.split(';base64,')[1];

You could also do

var base64=reader.result.replace(/^data:image\/\w+;base64,/, "");

You can use the following regex to replace any kind of data type:

const base64 = reader.result.toString().replace(/^data:(.*,)?/, "");