【JS学习】 FileReader | blob ...

2020-07-07  本文已影响0人  前端菜篮子

聊聊JS的二进制家族:Blob、ArrayBuffer和Buffer

Blob对象和string字符串


//字符串转Blob
var blob = new Blob(["Hello World!"], {
    type: 'text/plain'
});
console.info(blob);
//下面slice后的blob转成字符串 "el"
console.info(blob.slice(1, 3, 'text/plain'));  

//Blob转字符串      
var reader = new FileReader();
reader.readAsText(blob, 'utf-8');
reader.onload = function (e) {
    //得到的字符串:e.target和reader一样
    console.log(e.target.result, "e.target.result")
    console.info(reader.result, "reader.result");
}

Blob对象转换成ArrayBuffer

//将字符串转换成 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 

    //将 ArrayBufferView  转换成Blob
    var 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); //中文字符串
    };
}


Blob转

let reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = function(e) {
     //如果是pdf文件,这样就可直接预览
    window.open(URL.createObjectURL(blob));
    //或者
    let previewUrl = e.target.result   
    //将上面的previewUrl放入iframe
    /**<iframe style="width:100%;min-height:400px;" 
    :src="previewUrl" />*/
}


string字符串或blob作为文件下载

let blob = new Blob([content])
/**let reader = new FileReader()
  reader.readAsDataURL(blob)
  reader.onload = function(e) {
//若是pdf则可以直接预览了
  window.open(URL.createObjectURL(blob))
}*/
let fileName = 'text.txt';
// 非IE下载
if ('download' in document.createElement('a')) {  
  let link = document.createElement('a')
  link.download = fileName
  link.style.display = 'none'
  link.href = URL.createObjectURL(blob)
  document.body.appendChild(link)
  link.click()
  // 释放URL 对象
  URL.revokeObjectURL(link.href) 
  document.body.removeChild(link)
// IE10+下载
} else { 
  navigator.msSaveBlob(blob);
}
上一篇下一篇

猜你喜欢

热点阅读