当前位置:网站首页>Blob object introduction

Blob object introduction

2022-07-07 08:06:00 DIU DIU's great God

Blob Object represents an immutable 、 Class file object of original data . Its data can be read in text or binary format , It can also be converted into ReadableStream For data manipulation .

Look at the code below , You can use text construction Blob object

var debug = {
    hello: "world"};
var blob = new Blob([JSON.stringify(debug, null, 2)], {
    type : 'application/json'});

Example : Use Blob Create a pointer to a typed array URL

var typedArray = GetTheTypedArraySomehow();
var blob = new Blob([typedArray.buffer], {
    type: 'application/octet-stream'}); //  Pass in a suitable  MIME  type 
var url = URL.createObjectURL(blob);
//  It's going to produce something like  blob:d3958f5c-0777-0845-9dcf-2cb28783acaf  In this way  URL  character string 
//  You can use it like an ordinary  URL  Use it like that , For example, in  img.src  On .

Another read Blob The way of content in is to use Response object .

var text = await (new Response(blob)).text();

Sometimes the background download file is returned to the front end and converted to Blob object , During normal download , Return the correct file stream , When abnormal , The background returns a segment containing error information json , At this time, you need to prompt the user that the download failed , Look at the code below

/** *  format  blob  Return value  * @param {*} res */
const formatBlobResponse = async (res) => {
    
  const text = await new Response(res).text();
  let textObj = {
    };
  try {
    
    textObj = JSON.parse(text);
  } catch (e) {
    }

  if (text === '' || (textObj.code && Number(textObj.code) !== 200)) {
    
    return {
    
      success: false,
      msg: textObj.msg || ' Download file failed , Please contact the Administrator ',
    };
  } else {
    
    return {
    
      success: true,
      data: res,
    };
  }
};
原网站

版权声明
本文为[DIU DIU's great God]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070458351771.html