我无法将数据从Java发送到Javascript,反之亦然。
到目前为止,我已经尝试过了://a function I found online I use it to convert the decoded version of the java base64 byte[] to an ArrayBuffer
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));//retuns a different value than what I put into the buffer.
}
我真的不知道如何解决这个问题了吗?
答案 0 :(得分:6)
使用import com.sun.org.apache.xml.internal.security.utils.Base64;
npm install --production
产生
byte[] b = new byte[] { 12, 3, 4, 5, 12 , 34, 100 };
String encoded = Base64.encode(b);
"DAMEBQwiZA=="
产生
var stringToByteArray = function(str) {
var bytes = [];
for (var i = 0; i < str.length; ++i) {
bytes.push(str.charCodeAt(i));
}
return bytes;
};
var decoded = stringToByteArray(atob("DAMEBQwiZA=="));
注意:如果您在NodeJS中执行此操作,请查看atob包。