前端canvas截图上传

2020-06-12  本文已影响0人  朱传武

截图blob转换成base64:

export const getBlobWithUrl=(url)=>{
  return new Promise((resolve,reject)=>{
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) {
    if (this.status == 200) {
       let blob = this.response;let reader = new FileReader();
       reader.onload=function(e) {
           resolve(e.target.result);
       }
       reader.readAsDataURL(blob);
   // myBlob is now the blob that the object URL pointed to.
   }
 };
 xhr.send();
  });
}

blob/base64 转成file

export const dataURLtoFile=(dataurl)=> {
  let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while(n--){
      u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr],`${new Date().getTime()}.jpg`, {type:mime});
}

文件上传:

export const upLoadFile=(ImageFile)=> {
 return new Promise((resolve,reject)=>{
  let formData = new FormData();
  formData.append("file", ImageFile);
  formData.append("file_prefix", "hanbang");
  let request = new XMLHttpRequest();
  request.open("POST", `https://wxqrcode.3vyd.com/store/file/upload`);
  request.setRequestHeader("authorization", token);
  request.onload = function(e) {
    if (this.status == 200) {
          resolve(e.target.response);
    } else {
      reject(e);
    }
   }
  request.send(formData);
 });
}
上一篇下一篇

猜你喜欢

热点阅读