前端小工具:UTILS

将图片base64转换为文件
/**
 * 将base64转换为文件
 * @param dataurl 
 * @param filename 
 */
export function dataURLtoFile(dataurl, filename) {
  let arr = dataurl.split(',');
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length; 
  let u8arr = new Uint8Array(n);
  while(n--){
      u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {type:mime});
}

获取文件流

function handleGetBlob(baseUrl) {
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest()
      xhr.open('GET', baseUrl, true)
      xhr.responseType = 'blob'
      xhr.onload = function(option:any) {
        let res = option.target
        if (res.status === 200) {
          const bloburl = window.URL.createObjectURL(res.response)
          resolve(bloburl)
        }else{
          reject(baseUrl)
        }
      }
      xhr.send()
    })
  }

下载文件流

function downloadFileByBlob(url:string, filename?: string){
    new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = () => {
            if (xhr.status === 200) {
            console.log(xhr.getResponseHeader('Content-Type'))
            resolve(xhr.response);
            }
        };
        xhr.send();
    }).then(res=>{
        let aElement = document.createElement("a")
        aElement.download = filename || `${Date.now()}.xlsx`
        aElement.style.display = 'none'
        aElement.href = URL.createObjectURL(res)
        document.body.appendChild(aElement)
        aElement.click()
        document.body.removeChild(aElement)
    })
}

export default downloadFileByBlob;

 

兼容IE,  cancas,toBlod装换方法

if(!HTMLCanvasElement.prototype.toBlob){
      Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
        value:function(callback,type,quality){
        // eslint-disable-next-line @typescript-eslint/no-this-alias
        let canvas = this;
        setTimeout(function () {
          let binStr = atob(canvas.toDataURL(type, quality).split(',')[1]);
          let len = binStr.length;
          let arr = new Uint8Array(len);
          for (let i = 0; i < len; i++) {
            arr[i] = binStr.charCodeAt(i);
            }
            callback(new Blob([arr], {
              type: type || 'image/png'
            }));
          });
        }
      });
    }

session二次封装

interface StoreType {
  set: (name: string, data:any) => void
  get: (name: string) => void
  remove: (name: string) => void
  clear: ()=>void
  getKey: (index: number)=>void
}

function key2LowerCase(name: string) {
  if(!name) return null
  return `_${name.toLocaleLowerCase()}_`;
}
/**
 * sessionStorage
 */
export const sessionStore:StoreType = {
  set(name: string, data: any) {
    let value = null;
    if (data === undefined || data === null || isNaN(data)) {
      return false;
    }
    if (typeof data === 'string'|| typeof data === 'number') {
      value = data;
    } else {
      value = JSON.stringify( data )
    }
    let key =  key2LowerCase(name)
    sessionStorage.setItem(key, value)
  },
  get(name:string) {
    let key = key2LowerCase(name)
    let data = null;
    try {
      data = JSON.parse(sessionStorage.getItem(key))
    } catch (error) {
      data = sessionStorage.getItem(key)
    }
    return data;
  },
  remove(name: string) {
    let key = key2LowerCase(name)
    sessionStorage.removeItem(key)
  },
  clear() {
    sessionStorage.clear()
  },
  getKey(index:number) {
    sessionStorage.key(index)
  }
  
}
/**
 * localStorage
 */
export const localStore:StoreType = {
  set(name: string, data: any) {
    let value = null;
    if (data === undefined || data === null || isNaN(data)) {
      return false;
    }
    if (typeof data === 'string'|| typeof data === 'number') {
      value = data;
    } else {
      value = JSON.stringify( data )
    }
    let key =  key2LowerCase(name)
    localStorage.setItem(key, value)
  },
  get(name:string) {
    let key = key2LowerCase(name)
    let data = null;
    try {
      data = JSON.parse(localStorage.getItem(key))
    } catch (error) {
      data = localStorage.getItem(key)
    }
    return data;
  },
  remove(name: string) {
    let key = key2LowerCase(name)
    localStorage.removeItem(key)
  },
  clear() {
    localStorage.clear()
  },
  getKey(index:number) {
    localStorage.key(index)
  }
  
}

是否是IE

export const isIE = function () {
    const userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
    const isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; // 判断是否IE<11浏览器
    const isEdge = userAgent.indexOf("Edge") > -1 && !isIE; // 判断是否IE的Edge浏览器
    const isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    return isIE || isEdge || isIE11
}

 

没有终点,没有彼岸,坚持就好,愿岁月如初

posted @ 2021-01-09 16:18  smallbore  阅读(291)  评论(0编辑  收藏  举报
回顶部