vue3 base64文件传oss

2024-09-11  本文已影响0人  我是七月
const uploadBase64ToOSS = (base64,ossConfig)=>{

  // 将Base64转换为Blob
  function dataURLtoBlob(dataurl) {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = window.atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }
 
  console.log("dataURLtoBlob(base64)==",dataURLtoBlob(base64))

  // 生成随机文件名
  const randomFilename = `${Date.now()}-${generateUUIDv4()}`;
 
  // 创建FormData
  const formData = new FormData();
  formData.append('key', ossConfig.key); // OSS文件路径
  formData.append('OSSAccessKeyId', ossConfig.OSSAccessKeyId);
  formData.append('policy', ossConfig.policy);
  formData.append('signature', ossConfig.signature);
  formData.append('file', dataURLtoBlob(base64), randomFilename);
 
  // 发送请求
  return axios.post(ossConfig.action, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}
     uploadBase64ToOSS(imageData.url,ossConfigData).then(response => {
                console.log('上传成功', response);
            }).catch(error => {
                ossCount.value  = ossCount.value +1
                console.error('上传失败====', error);
            });
上一篇下一篇

猜你喜欢

热点阅读