云计算百科
云计算领域专业知识百科平台

Base64 上传到阿里云 OSS

Canvas 截图是 Base64 格式,我要把它上传到阿里云 OSS。但 OSS 的 FormData 上传不支持 Base64。

第一步:Base64 转 Blob

const uploadBase64ToOss = async (base64Str, directory = "files") => {
// 解析 base64
const arr = base64Str.split(",");
const mime = arr[0].match(/:(.*?);/)[1]; // e.g. image/png
const bstr = atob(arr[1]);
const n = bstr.length;
const u8arr = new Uint8Array(n);

while (n–) {
u8arr[n] = bstr.charCodeAt(n);
}

// 构造 Blob
const blob = new Blob([u8arr], { type: mime });

// … 后续上传逻辑
};

atob 把 Base64 字符串转成二进制字符串,然后逐个字符转成 Uint8Array。

第二步:构造 FormData

// 获取 OSS 临时签名
const signData = await getSign(directory);

// 时间戳文件名
const timestamp = new Date().getTime();
const fileExt = mime.split("/")[1] || "bin"; // e.g. png
const fileName = `${timestamp}.${fileExt}`;

// OSS 表单数据
const formData = new FormData();
formData.append("OSSAccessKeyId", signData.data.accessId);
formData.append("policy", signData.data.policy);
formData.append("signature", signData.data.signature);
formData.append("key", `${directory}/${fileName}`);
formData.append("success_action_status", "200");
formData.append("file", blob, fileName);

第三步:用 fetch 上传

const response = await fetch("https://<bucket-name>.<region>.aliyuncs.com", {
method: "POST",
body: formData,
});

if (response.status === 200) {
return `https://<bucket-name>.<region>.aliyuncs.com/${directory}/${fileName}`;
} else {
throw new Error("上传失败");
}

为什么不用 XMLHttpRequest?

之前上传文件用的是 XMLHttpRequest,但 Base64 转 Blob 后,用 fetch 更简洁:

// ❌ XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.onload = () => resolve(xhr.status === 200 ? url : null);
xhr.onerror = reject;
xhr.send(formData);

// ✅ fetch
const response = await fetch(url, { method: 'POST', body: formData });
return response.status === 200 ? url : null;

几个踩坑总结
  • Base64 要去掉前缀:split(",")[1] 只取数据部分
  • MIME type 从 Base64 提取:用正则 /:(.*?);/
  • 文件扩展名从 MIME 提取:mime.split("/")[1]
  • Blob 构造要指定 type:new Blob([u8arr], { type: mime })
  • fetch 比 XHR 简洁:异步代码更易读
  • 赞(0)
    未经允许不得转载:网硕互联帮助中心 » Base64 上传到阿里云 OSS
    分享到: 更多 (0)

    评论 抢沙发

    评论前必须登录!