这个问题在过去已经得到了答案,但我肯定会说它仍然没有得到答案。
一般来说,几乎有关于ArrayBuffers的文档,更不用说特定的应用程序了。我一直在研究这几天无济于事。
基本上我需要尝试将从文件阅读器(此处:https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer)获取的ArrayBuffer转换为字符串,然后将该字符串转换回相同的ArrayBuffer。
我尝试过这些方法,例如
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
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 b
我收到以下错误:&#34; Uint16Array的字节长度应该是2的倍数&#34;
我也试过以下
function StringToUint8Array(string) {
var binary, binLen, buffer, chars, i, _i;
binary = StringToBinary(string);
binLen = binary.length;
buffer = new ArrayBuffer(binLen);
chars = new Uint8Array(buffer);
for (i = _i = 0; 0 <= binLen ? _i < binLen : _i > binLen; i = 0 <= binLen ? ++_i : --_i) {
chars[i] = String.prototype.charCodeAt.call(binary, i);
}
return chars;
}
function ArrayBufferToString(buffer) {
return BinaryToString(String.fromCharCode.apply(null, Array.prototype.slice.apply(new Uint8Array(buffer))));
}
function StringToArrayBuffer(string) {
return StringToUint8Array(string).buffer;
}
function BinaryToString(binary) {
var error;
try {
return decodeURIComponent(escape(binary));
} catch (_error) {
error = _error;
if (error instanceof URIError) {
return binary;
} else {
throw error;
}
}
}
function StringToBinary(string) {
var chars, code, i, isUCS2, len, _i;
len = string.length;
chars = [];
isUCS2 = false;
for (i = _i = 0; 0 <= len ? _i < len : _i > len; i = 0 <= len ? ++_i : --_i) {
code = String.prototype.charCodeAt.call(string, i);
if (code > 255) {
isUCS2 = true;
chars = null;
break;
} else {
chars.push(code);
}
}
if (isUCS2 === true) {
return unescape(encodeURIComponent(string));
} else {
return String.fromCharCode.apply(null, Array.prototype.slice.apply(chars));
}
}
并收到此错误:超出最大调用堆栈大小
以下转换似乎没有好的方法:AB - &gt;字符串||字符串 - &gt; AB
答案 0 :(得分:1)
以下是对出色答案的补充,以下是转换功能的TypeScript版本
const arrayBufferToString = (buffer: ArrayBuffer, encoding = 'UTF-8'): Promise<string> => {
return new Promise<string>((resolve, reject) => {
const blob = new Blob([buffer], { type: 'text/plain' });
const reader = new FileReader();
reader.onload = (evt) => {
if (evt.target) {
resolve(evt.target.result as string);
} else {
reject(new Error('Could not convert array to string!'));
}
};
reader.readAsText(blob, encoding);
});
};
const stringToArrayBuffer = (text: string, encoding = 'UTF-8'): Promise<ArrayBuffer> => {
return new Promise<ArrayBuffer>((resolve, reject) => {
const blob = new Blob([text], { type: `text/plain;charset=${encoding}` });
const reader = new FileReader();
reader.onload = (evt) => {
if (evt.target) {
resolve(evt.target.result as ArrayBuffer);
} else {
reject(new Error('Could not convert string to array!'));
}
};
reader.readAsArrayBuffer(blob);
});
};
答案 1 :(得分:1)
现在大多数浏览器具有TextEncoder
,而Node具有util.TextEncoder
。该WHATWG标准提供了在字节数组和字符串之间进行转换的简单方法:
const str = new TextEncoder().decode(byteArray);
const byteArray = new TextEncoder().encode(str);
答案 2 :(得分:0)
使用Blob和FileReader有一种异步方式。
您可以指定任何有效的编码。
function arrayBufferToString( buffer, encoding, callback ) {
var blob = new Blob([buffer],{type:'text/plain'});
var reader = new FileReader();
reader.onload = function(evt){callback(evt.target.result);};
reader.readAsText(blob, encoding);
}
function stringToArrayBuffer( string, encoding, callback ) {
var blob = new Blob([string],{type:'text/plain;charset='+encoding});
var reader = new FileReader();
reader.onload = function(evt){callback(evt.target.result);};
reader.readAsArrayBuffer(blob);
}
//example:
var buf = new Uint8Array([65,66,67]);
arrayBufferToString(buf, 'UTF-8', console.log.bind(console)); //"ABC"
stringToArrayBuffer('ABC', 'UTF-8', console.log.bind(console)); //[65,66,67]