安裝插件 browser-md5-file
browser-md5-file 用於計算文件md5,文檔介紹較少,看看就能使用↓
使用例子
- 比如我用 el-upload 組件上傳圖片
<el-upload
action=""
class="upload-box"
:show-file-list="false"
accept=".jpg,.jpeg,.png"
:http-request="(rawFile:any) => uploadFileToOss(rawFile,index)"
>
<svg-icon name="upload" class="icon"></svg-icon>
</el-upload>
- 對文件進行包裝(這個主要看個人項目實際需要)
const uploadFileToOss = async (rawFile: any, index: number) => {
const data = await uploadOss({
name: rawFile.file.name,
file: rawFile.file,
});
propsList.value[index][propsList.value[index].id] = data.url;
ElMessage.success('上傳成功');
};
- 上傳文件到 OSS ,先處理文件——>獲取簽名——>最後上傳到 oss
import BMF from 'browser-md5-file'; // 用於計算文件md5:https://www.npmjs.com/package/browser-md5-file
type File = any;
type OssConfig = {
accessid: string | Blob;
policy: string | Blob;
signature: string | Blob;
key: string | Blob;
host: any;
};
type OnUploadProgress = (progressEvent: any) => void;
// 上傳文件到OSS
export async function uploadOss(
file: File,
onUploadProgress?: OnUploadProgress,
ossUrl?: string,
) {
if (!file) {
return null;
}
// 對文件進行md5計算,節省雲端存儲空間
const bmf = new BMF();
const md5 = await new Promise((resolve, reject) => {
bmf.md5(
file.file,
(err: any, md5: string) => {
if (err) {
reject(err);
}
resolve(md5);
},
(progress: number) => {
console.log('progress number:', progress);
},
);
});
const name = file.name;
const suffix = name.substring(name.lastIndexOf('.'), name.length);
// 文件路徑: xxx/文件md5值.文件後綴
const filePath = `xxx/${md5}${suffix}`;
// 1.獲取OSS簽名
let r = await getOssSignature(filePath, ossUrl);
// 2.開始上傳文件到OSS
await uploadStart(file.file, r.data, onUploadProgress);
return r.data;
}
// 獲取OSS簽名
async function getOssSignature(filePath: any, ossUrl: any) {
ossUrl = ossUrl ? ossUrl : '/xxx/xxx';
let res = await request({
url: ossUrl,
method: 'get',
params: { filePath },
});
return res;
}
// 上傳文件開始準備
async function uploadStart(
file: File,
ossConfig: OssConfig,
onUploadProgress?: OnUploadProgress,
) {
// 組裝發送數據
let formData = new FormData();
formData.append('OSSAccessKeyId', ossConfig.accessid); // Bucket
// 擁有者的Access
// Key Id。
formData.append('policy', ossConfig.policy); // policy規定了請求的表單域的合法性
formData.append('signature', ossConfig.signature); // 根據Access Key
// Secret和policy計算的簽名信息,OSS驗證該簽名信息從而驗證該Post請求的合法性
// ---以上都是阿里的認證策略
formData.append('key', ossConfig.key); // 文件名字,可設置路徑
formData.append('success_action_status', '200'); // 讓服務端返回200,不然,默認會返回204
formData.append('file', file); // 需要上傳的文件 file
let data = await request({
url: ossConfig.host,
method: 'post',
data: formData,
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: onUploadProgress,
withCredentials: false,
});
return data;
}