[JavaScript]使用ArrayBuffer和Blob編輯二進制流


Blob()構造方法返回一個新的Blob對象. 內容是包含參數array的二進制字節流.

語法

var aBlob = new Blob( array, options );

參數

  • array is an Array of ArrayBuffer, ArrayBufferView, Blob, DOMString objects, or a mix of any of such objects, that will be put inside the Blob. DOMStrings are encoded as UTF-8.
  • options is an optional BlobPropertyBag dictionary which may specify the following two attributes:
    • type, with a default value of "", that represents the MIME type of the content of the array that will be put in the blob.
    • endings, with a default value of "transparent", that specifies how strings containing the line ending character \n are to be written out. It is one of the two values: "native", meaning that line ending characters are changed to match host OS filesystem convention, or "transparent", meaning that endings are stored in the blob without change.
var buffer = new ArrayBuffer(2);
var int8View = new Int8Array(buffer);
int8View[0] = 170;
int8View[1] = 254;

var blob = new Blob([int8View, event.target.result]);

 此段代碼創建了一個2字節的二進制數10101010和11111110,並且把它追加到了event.target.result字節流的頭部

var buffer = new ArrayBuffer(8);
var uInt32 = new Uint32Array(buffer);
uInt32[0]  = 2356021;

console.log(uInt32[0]); // 2356021
console.log(uInt32.length); // 2
console.log(uInt32.BYTES_PER_ELEMENT); // 4

var view = new DataView(buffer,0,8);
console.log(view.getUint32(0,4));//2356021

此段代碼創建了2個無符號32位整數buff(一個unsigned int需要4個字節空間,所以new ArrayBuffer(8)分配了8個字節,即,可容納8/4=2個unsigned int類型的整數);

在第1個數組放置2356021,當然你可以使用uInt32[1]放置第二個值,但是你只能放置2個值,畢竟它只分配了8/4=2個unsigned int類型的整數;

調用length可查看ArrayBuffer的長度,這里是2,調用BYTES_PER_ELEMENT可查看每個元素占用的字節數,這里是4;

運用DataView可以以一種方式去讀取某段buff的值;

 查看更多的例子:

運用XHR異步請求接收二進制流


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM