前端-上传文件/图片至oss服务
1. 获取服务器目录信息
//getOssXXXX 获取服务器目录信息Api
//fileType 文件类格式
//ossAuthority 文件属性 1公开 2 私有
const policyResult: any = await getOssXXXX({ fileType: 'png', ossAuthority: 1 });
//host 域名地址 viewurl 上传后的目录地址 accessKeyId 访问密钥id signature 签名 policy字符串 key 路径后缀
const { host, viewurl, accessKeyId, signature, policy, key } = policyResult.data.model;
2. 上传操作,调用对应的上传方法(以taro为例)
// filePath 选择的文件路径
const uploadResult = await Taro.uploadFile({
url: host, // 开发者服务器的URL。
filePath: filePath, //选择的文件路径
name: 'file', // 文件类型
formData: {
key,
policy,
OSSAccessKeyId: accessKeyId,
signature,
success_action_status: '200',
},
}) || {};
if (uploadResult?.statusCode === 200) {
console.log(viewurl) // 上传成功的地址
}
2.1 如果没有上传方法,则手动上传操作
1. 路径转Base64
// filePath 选择的文件路径
const chooseImagePathToBase64 = async (filePath: string) => {
const result = await fetch(filePath);
const blob = await result.blob();
return new Promise(resolve => {
const reader = new FileReader();
reader.onloadend = img => {
resolve(img.target?.result); // return base64 string
};
reader.readAsDataURL(blob);
});
};
const path = await chooseImagePathToBase64(filePath);
2.转过后的路径,上传文件
// 将base64转换为blob方法
const base64toBlob = (base64: string) => {
const arr = base64.split(',');
const mime = arr[0].match(/:(.*?);/)?.[1];
const bstr = 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,
});
};
interface IPostOssPayload {
accessid: string;
signature: string;
policy: string;
dir: string;
}
// base64转blob上传
const uploadFileBase = async (base64Data: any, url: string, query: IPostOssPayload) => {
let blob: any = '';
if (base64Data.indexOf('base64') > -1) {
blob = base64toBlob(base64Data);
} else {
blob = base64toBlob(`data:image/png;base64,${base64Data}`);
}
const formdata = new FormData();
formdata.append('OSSAccessKeyId', query?.accessid);
formdata.append('signature', query?.signature);
formdata.append('policy', query?.policy);
formdata.append('key', query?.dir);
formdata.append('success_action_status', '204');
formdata.append('file', blob);
try {
const result = await fetch(url, {
method: 'POST',
body: formdata,
});
return result;
} catch (error) {
throw error
}
};
const result = await uploadFileBase(path, host, {
accessid,
dir,
policy,
signature,
});
if (result?.status === 204) {
console.log(viewurl) //上传成功的地址
}

浙公网安备 33010602011771号