html string转换byte,HTML5 Blob与ArrayBuffer、TypeArray和字符串String之间转换

1.将String字符串转换成Blob对象

ffe58194a0a6e23633430cd5d25cab33.gif

//将字符串 转换成 Blob 对象

var blob = new Blob(["Hello World!"], {

type: 'text/plain'

});

console.info(blob);

console.info(blob.slice(1, 3, 'text/plain'));

b992f8340121b18322922b735c2977e3.gif

2.将TypeArray  转换成 Blob 对象

1dbb0e4f5cae2b730443fcbd9d107177.gif

//将 TypeArray 转换成 Blob 对象

var array = new Uint16Array([97, 32, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]);

//测试成功

//var blob = new Blob([array], { type: "application/octet-binary" });

//测试成功, 注意必须[]的包裹

var blob = new Blob([array]);

//将 Blob对象 读成字符串

var reader = new FileReader();

reader.readAsText(blob, 'utf-8');

reader.onload = function (e) {

console.info(reader.result); //a Hello world!

}

57d10716793df01cd78a7255732ea05f.gif

ArrayBuffer转Blob

var buffer = new ArrayBuffer(32);

var blob = new Blob([buffer]); // 注意必须包裹[]

3,将Blob对象转换成String字符串,使用FileReader的readAsText方法

536b913044980525b9109cf489f6b74e.gif

//将字符串转换成 Blob对象

var blob = new Blob(['中文字符串'], {

type: 'text/plain'

});

//将Blob 对象转换成字符串

var reader = new FileReader();

reader.readAsText(blob, 'utf-8');

reader.onload = function (e) {

console.info(reader.result);

}

b3175ac502232d700948799c719563a7.gif

4.将Blob对象转换成ArrayBuffer,使用FileReader的 readAsArrayBuffer方法

d25decb4ef337344a25315f89d80b8d8.gif

//将字符串转换成 Blob对象

var blob = new Blob(['中文字符串'], {

type: 'text/plain'

});

//将Blob 对象转换成 ArrayBuffer

var reader = new FileReader();

reader.readAsArrayBuffer(blob);

reader.onload = function (e) {

console.info(reader.result); //ArrayBuffer {}

//经常会遇到的异常 Uncaught RangeError: byte length of Int16Array should be a multiple of 2

//var buf = new int16array(reader.result);

//console.info(buf);

//将 ArrayBufferView 转换成Blob

var buf = new Uint8Array(reader.result);

console.info(buf); //[228, 184, 173, 230, 150, 135, 229, 173, 151, 231, 172, 166, 228, 184, 178]

reader.readAsText(new Blob([buf]), 'utf-8');

reader.onload = function () {

console.info(reader.result); //中文字符串

};

//将 ArrayBufferView 转换成Blob

var buf = new DataView(reader.result);

console.info(buf); //DataView {}

reader.readAsText(new Blob([buf]), 'utf-8');

reader.onload = function () {

console.info(reader.result); //中文字符串

};

}

b9d13e8bd9026839efcef271aa852cff.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值