[转] HTML5 Blob与ArrayBuffer、TypeArray和字符串String之间转换
生活随笔
收集整理的這篇文章主要介紹了
[转] HTML5 Blob与ArrayBuffer、TypeArray和字符串String之间转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.將String字符串轉換成Blob對象
//將字符串 轉換成 Blob 對象 var blob = new Blob(["Hello World!"], {type: 'text/plain' }); console.info(blob); console.info(blob.slice(1, 3, 'text/plain'));2.將TypeArray ?轉換成 Blob 對象
//將 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! }ArrayBuffer轉Blob
?
var buffer = new ArrayBuffer(32); var blob = new Blob([buffer]); // 注意必須包裹[]?
?
?
3,將Blob對象轉換成String字符串,使用FileReader的readAsText方法
//將字符串轉換成 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); }4.將Blob對象轉換成ArrayBuffer,使用FileReader的?readAsArrayBuffer方法
//將字符串轉換成 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 轉換成Blobvar 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 轉換成Blobvar buf = new DataView(reader.result);console.info(buf); //DataView {}reader.readAsText(new Blob([buf]), 'utf-8');reader.onload = function () {console.info(reader.result); //中文字符串}; }關于Blob對象,請參考:http://www.cnblogs.com/tianma3798/p/4293660.html
轉載于:https://www.cnblogs.com/chris-oil/p/8609118.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的[转] HTML5 Blob与ArrayBuffer、TypeArray和字符串String之间转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 不一样的Office 365之 —— M
- 下一篇: 网页编辑器