首页 > 编程语言 >Javascript: Blob, File/FileReader, ArrayBuffer, ReadableStream, Response 转换方法

Javascript: Blob, File/FileReader, ArrayBuffer, ReadableStream, Response 转换方法

时间:2024-07-17 17:23:46浏览次数:8  
标签:const FileReader ArrayBuffer 转换方法 ReadableStream Blob https org Response

目录

先上图

各个 Object

ArrayBuffer:

1.  ArrayBuffer 是 JavaScript 中的一种数据类型,用于表示通用的、固定长度的二进制数据缓冲区。
    
2.  ArrayBuffer 对象表示内存中的一段二进制数据,并且不能直接操作这些数据,需要使用 TypedArray 或 DataView 对象来操作。
    
3.  可以通过 ArrayBuffer 构造函数创建一个指定长度的 ArrayBuffer 对象。

Blob:

1.  Blob 表示二进制大对象(Binary Large Object),通常用于表示文件或数据的片段。
    
2.  Blob 对象可以包含任意类型的数据,包括文本数据、图像数据等。
    
3.  可以使用 Blob 构造函数创建一个新的 Blob 对象,也可以通过 BlobBuilder 或 Blob 的静态方法创建。

File:

1.  File 对象是 Blob 的子类,表示文件的一种特殊类型。
    
2.  File 对象通常用于表示用户通过文件选择器选择的文件。
    
3.  File 对象包含文件的元数据,如文件名、大小、类型等。

FileReader:

1.  FileReader 对象`唯一目的`是读取文件或 Blob 对象中的数据,并将其转换为String或 ArrayBuffer。
    
2.  FileReader 提供了异步读取文件的接口,可以监听 load 事件来处理读取完成后的数据。
    
3.  通过调用 FileReader 对象的 readAsText() 方法可以将文件或 Blob 中的数据读取为字符串,而调用 readAsArrayBuffer() 方法则可以将数据读取为 ArrayBuffer。

ReadableStream:

1.  ReadableStream 是 JavaScript 中的流对象,用于表示可读取的数据流。
    
2.  ReadableStream 对象提供了一种从数据源(如网络请求、文件等)读取数据的方式,可以逐个读取数据并进行处理。
    
3.  ReadableStream 对象通常用于处理大型数据流,如网络请求响应、文件读取等。

综上所述,ArrayBuffer、Blob、File、FileReader 和 ReadableStream 是 JavaScript 中用于处理二进制数据和文件的重要对象和接口。它们可以配合使用,实现对文件和数据的读取、处理和传输。

Response

Response 对象是浏览器 Fetch API 提供的一种接口,用于表示 HTTP 响应。它包含了响应的各种信息,如响应状态码、响应头部、响应体等,以及一些用于处理响应数据的方法。

以下是 Response 对象的一些常用属性和方法:

  1. status: 表示 HTTP 响应的状态码。

  2. statusText: 表示 HTTP 响应状态码的文本描述。

  3. headers: 表示响应头部信息的 Headers 对象。

  4. ok: 表示响应是否成功,即状态码是否在 200 到 299 之间。

  5. url: 表示响应的 URL。

  6. body: 表示响应的主体部分,可以是 ReadableStream、Blob、FormData、BufferSource 等类型。

  7. text(): 以文本形式读取响应的主体部分。

  8. json(): 以 JSON 格式解析响应的主体部分。

  9. blob(): 以 Blob 对象形式读取响应的主体部分。

  10. arrayBuffer(): 以 ArrayBuffer 对象形式读取响应的主体部分。

用法举例

ArrayBuffer

// 创建一个长度为 8 字节的 ArrayBuffer
const buffer = new ArrayBuffer(8);

// 使用 Int32Array 视图操作 ArrayBuffer 中的数据
const intArray = new Int32Array(buffer);
intArray[0] = 123;
console.log(intArray); // 输出: Int32Array [ 123, 0, 0, 0 ]

Blob, File, FileReader

  • FileReader 读取 Blob
// 创建一个包含文本内容的 Blob 对象
const blob = new Blob(['Hello, world!'], { type: 'text/plain' });

// 创建一个 FileReader 对象
const reader = new FileReader();

// 监听 FileReader 对象的 load 事件
reader.onload = function(event) {
  // 读取完成后,event.target.result 中存储了转换后的字符串
  const resultString = event.target.result;
  console.log(resultString); // 输出: Hello, world!
};

// 将 Blob 对象中的数据读取为字符串
reader.readAsText(blob);
  • FileReader 读取 File 对象
<input type="file" id="fileInput">
<script>
  document.getElementById('fileInput').addEventListener('change', function(event) {
    const file = event.target.files[0]; // 获取用户选择的文件
    console.log(file.name); // 输出文件名

    const reader = new FileReader();
    reader.onload = function(event) {
      const resultString = event.target.result;
      console.log(resultString); // 输出文件内容
    };
    reader.readAsText(file); // 读取文件内容为字符串
  });
</script>

ReadableStream

  • 示例1
async function main() {
  // 创建一个 ReadableStream 对象,用于从指定 URL 中读取数据
  const promise = fetch('https://www.baidu.com')

  const response = await promise

  const bodyStream = response.body

  // 创建一个 StreamReader 对象,用于读取数据流
  const reader = bodyStream.getReader()

  const arrayArray = []

  while (true) {
    // 读取数据流的一部分并处理
    const { done, value } = await reader.read()
    if (done) {
      console.log('读取完成, 输出结果:')
      const str = await uint8ArrayToString(arrayArray)
      console.log(str.slice(0, 300))
      break
    }
    console.log('读取到新数据, length:', value.length)
    arrayArray.push(value)
  }
}

async function uint8ArrayToString(arrayArray) {
  const blob = new Blob(arrayArray, { type: 'text/plain' })
  const text = await blob.text()
  return text
}

main()
  • 示例2
fetch('https://www.example.org/').then((response) => {
  const reader = response.body.getReader()
  const stream = new ReadableStream({
    start(controller) {
      // The following function handles each data chunk
      function push() {
        // "done" is a Boolean and value a "Uint8Array"
        return reader.read().then(({ done, value }) => {
          // Is there no more data to read?
          if (done) {
            // Tell the browser that we have finished sending data
            controller.close()
            return
          }

          // Get the data and send it to the browser via the controller
          controller.enqueue(value)
          push()
        })
      }

      push()
    },
  })

  return new Response(stream, { headers: { 'Content-Type': 'text/html' } })
})

关于 ReadableStream 的一点总结

fetch() 返回的是一个 Promise, 该 Promise resolve 的结果是 Response 对象

Response.body 是一个 ReadableStream

ReadableStream.getReader 返回 [ReadableStreamDefaultReader](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) or [ReadableStreamBYOBReader](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader)

reader.read() 返回一个 Promise, 该 Promise resolve 的数据是一个Object { done, value }

reader 可以如下使用:

function run() {
  reader.read().then(({ done, value }) => {
    if (done) {
      // 没有更多数据了
      finished = true
      return
    }
    // deal with value
    //...
    run()
  })
}
run()

Response

构造函数

new Response()
new Response(body)
new Response(body, options)

Parameters

[body](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#body) Optional

An object defining a body for the response. This can be null (which is the default value), or one of:

  • [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob)

  • [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)

  • [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)

  • [DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)

  • [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData)

  • [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)

  • [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

  • [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)

  • string literal

[options](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#options) Optional

An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are:

[status](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#status)

The status code for the response. The default value is 200.

[statusText](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#statustext)

The status message associated with the status code, such as "OK". The default value is "".

[headers](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#headers)

Any headers you want to add to your response, contained within a [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object or object literal of [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) key/value pairs (see HTTP headers for a reference). By default this is empty.

blob()

const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => response.blob())
  .then((myBlob) => { // response.blob() 返回的是 Promise,这里的 then() 接收到的 myBlob 是
                      // Promise resolve 后的 blob
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });

标签:const,FileReader,ArrayBuffer,转换方法,ReadableStream,Blob,https,org,Response
From: https://www.cnblogs.com/dongling/p/18307858

相关文章

  • 怎么把webp格式转换成jpg?5个图片格式转换方法全面解析(2024最新)
    webp 图片常用于网站,可显著改善页面的浏览和加载体验。然而,许多设备(如苹果手机设备、安卓手机等)不支持webp文件。在这些设备上查看webp文件时,最佳做法是将其转换为其他常见格式,如jpg或png。Windows电脑上有多种转换工具可把webp格式转换成jpg。本文将分享5种webp图片格式转换......
  • 详谈JavaScript 二进制家族:Blob、File、FileReader、ArrayBuffer、Base64
    详谈JavaScript二进制家族:Blob、File、FileReader、ArrayBuffer、Base64:https://blog.csdn.net/weixin_43025151/article/details/129743443?ops_request_misc=&request_id=&biz_id=102&utm_term=JavaScript%E4%B8%AD%E7%9A%84Blob%E4%BD%A0%E7%9F%A5%E9%81%93%E5%A4%9A%E......
  • FileReader处理Blob对象
    使用axios下载文件时,当下载出错,后端返回错误信息时,需要先通过FileReader将Blob对象转换为文本,然后将文本转换为JSON对象,最后将JSON对象中的message属性作为错误信息展示给用户。constfileReader=newFileReader();fileReader.onload=function(e){constresult=fileR......
  • JavaScript---FileReader、Blob、File对象
    ArrayBuffer对象,Blob对象ArrayBuffer对象ArrayBuffer对象表示一段二进制数据,用来模拟内存里面的数据。通过这个对象,JavaScript可以读写二进制数据。这个对象可以看作内存数据的表达。这个对象是ES6才写入标准的,普通的网页编程用不到它,为了教程体系的完整,下面只提供一......
  • 微信小程序蓝牙红外发送ArrayBuffer合并字节数组
    微信小程序中与设备进行通讯时,经常需要在前面加一些字节,或者处理分包的时候需要加一些字节过去,如果在后端很好操作,但是在小程序中由于ArrayBuffer不支持直接操作,非常不方便最近一个与设备通讯中,需要添加前导字符,百度了一圈没有好的方案,东拼西凑了才算是搞出来了 functioncop......
  • 记录一下时间戳转换方法
    /***时间戳格式化函数*@param{string}format格式如('Y-m-d')*@param{number}timestamp要格式化的时间默认为当前时间,必须为number类型,字符串将返回NAN*@return{string}格式化的时间字符串,(按照上面的格式返回结果可以为'2023-01-01')......
  • jQuery对象与DOM对象之间的转换方法
    jQuery对象与DOM对象之间的转换方法刚开始学习jquery,可能一时会分不清楚哪些是jQuery对象,哪些是DOM对象。至于DOM对象不多解释,我们接触的太多了,下面重点介绍一下jQuery,以及两者相互间的转换。什么是jQuery对象?就是通过jQuery包装DOM对象后产生的对象。jQuery对象是jQuery独有的......
  • JS 中的二进制 - Blob 与 ArrayBuffer
    零、参考资料《图解+实战》File、Blob、TypedArray、DataViewJavaScript也有操作二进制的一天:聊ArrayBuffer和Blob聊聊JS的二进制家族:Blob、ArrayBuffer和Buffer一、定义宏观:Blob-表示一个不可变、原始数据的类文件对象,可读不可写微观:ArrayBuffer-表示通用的原始......
  • JS日期格式化转换方法
    Date.prototype.Format=function(fmt){//author:meizzvaro={"M+":this.getMonth()+1,//月份"d+":this.getDate(),//日"H+":this.getHours(),//小时"m+":this.getMinutes(),//分......
  • uniapp ArrayBuffer转16进度字符串 以及 十六进制转ASCII码
    1.ArrayBuffer转16进度字符串//ArrayBuffer转16进度字符串示例//ab2hex(buffer){//consthexArr=Array.prototype.map.call(//newUint8Array(buffer),//function(bit){//......