• [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 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异步请求接收二进制流

  • 相关阅读:
    vue , debounce 使用
    git 合并代码
    vue-snippet-模板
    旋转字符串
    给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。
    水仙花数[js]
    一道笔试题(vue,react)
    OC中一些基本概念
    如何添加渐变?
    UIBarButtonItem关于全局修改,局部修改
  • 原文地址:https://www.cnblogs.com/yiyide266/p/6351446.html
Copyright © 2020-2023  润新知