将base64编码的图片上传至七牛云

Cris

七牛官方文档的示例promise化

function formatPicBase64(picBase64) {
  // 去掉逗号之前的所有字符包括逗号
  let arr = picBase64.split(',');
  return picBase64.substring(arr[0].length + 1);
}

function genFileSize(str) {
  let fileSize;
  if (str.indexOf('=') > 0) {
    let indexOf = str.indexOf('=');
    str = str.substring(0, indexOf);
  }
  fileSize = parseInt(str.length - (str.length / 8) * 2, 10);
  return fileSize;
}

function getBody(xhr) {
  const text = xhr.responseText || xhr.response;
  if (!text) {
    return text;
  }

  try {
    return JSON.parse(text);
  } catch (err) {
    return text;
  }
}

/**
 * upload base64 image to qiniu
 */
export function putb64(picBase64, token, key, onprogress) {
  return new Promise((resolve, reject) => {
    const formattedPicBase64 = formatPicBase64(picBase64);
    const EncodedKey = window.btoa(key).replace(/\+/g, '-').replace(/\//g, '_');
    const url = `http://upload.qiniu.com/putb64/${genFileSize(formattedPicBase64)}/key/${EncodedKey}`;

    let xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.timeout = 3600000;

    // 经测试发现,此处不能根据七牛官网文档写的readyState === 4来判断,因为不能捕获错误 比如当传一个非法的picBase64时,依然resolve而不是reject
    // 根据下方的 xhr.status == 200 来判断
    // xhr.onreadystatechange = function () {
    //   if (xhr.readyState === 4) {
    //     resolve && resolve(getBody(xhr));
    //   }
    // };

    xhr.onload = () => {
      if (xhr.status !== 200) {
        reject && reject(xhr);
        return;
      }

      resolve && resolve(getBody(xhr));
    };

    xhr.ontimeout = (e) => {
      reject && reject(e);
    };

    xhr.onerror = (e) => {
      reject && reject(e);
    };

    xhr.upload.onprogress = (event) => {
      onprogress && onprogress(event, xhr);
    };

    xhr.setRequestHeader('Content-Type', 'application/octet-stream');
    // 此处注意: UpToken 之后有一个空格
    xhr.setRequestHeader('Authorization', `UpToken ${token}`);
    xhr.send(formattedPicBase64);
  });
}
阅读 60
33 声望
0 粉丝
0 条评论
你知道吗?

33 声望
0 粉丝
宣传栏