封装图片组件

This commit is contained in:
2022-06-10 15:41:33 +08:00
parent 8197140027
commit 38a3b348bd
57 changed files with 2899 additions and 181 deletions
+121
View File
@@ -0,0 +1,121 @@
import Taro from '@tarojs/taro';
import {UPLOAD_CDN_URL } from '@/common/constant'
import { GetSignApi } from '@/api/cdn'
export default () => {
const { fetchData: GetSign, state} = GetSignApi()
// 上传图片 获取auth,Policy
/*
scene 场景值,区分上传文件的根路径
type 类型值,区分上传业务bucket
*/
const getSecret = (scene, type) => {
return new Promise(async (resolve, reject) => {
const SAVE_PATH = `/${scene}/{filemd5}{day}{hour}{min}{sec}{.suffix}`;
let params = {
'method': 'post',
'save_key': SAVE_PATH
}
// 获取签名
let res = await GetSign(params)
if (res.success) {
resolve(res.data)
} else {
reject({
code: res.code || '9999',
msg: res.msg
});
}
})
}
const getFileType = (name) => {
if (!name) return false;
var imgType = ["gif", "jpeg", "jpg", "bmp", "png"];
var videoType = ["avi", "wmv", "mkv", "mp4", "mov", "rm", "3gp", "flv", "mpg", "rmvb", "quicktime"];
if (RegExp("\.?(" + imgType.join("|") + ")$", "i").test(name.toLowerCase())) {
return 'image';
} else if (RegExp("\.(" + videoType.join("|") + ")$", "i").test(name.toLowerCase())) {
return 'video';
} else {
return false;
}
}
/**
*
* @param {*} file 传入文件
* @param {String} secene 传入 'product'
* @param {String} type 传入 'product'
* @returns
*/
const uploadCDNImg = (file, secene, type) => {
let filetype = file.path
console.log('filetype::',filetype)
if (!getFileType(filetype)) {
Taro.showToast({
title: "上传文件类型错误",
icon: "none",
duration: 3800
})
return false
}
return new Promise((resolve, reject) => {
getSecret(secene, type)
.then(result => {
let res:any = result
console.log('bucket', res.bucket);
var formdata = {
'authorization': res.authorization,
'policy': res.policy,
}
const uploadTask = Taro.uploadFile({
url: `${UPLOAD_CDN_URL}${res.bucket}`,
formData: formdata,
filePath: file.path,
name: 'file',
success: res => {
resolve(JSON.parse(`${res.data}`))
},
fail: err => {
console.log(err)
reject(err)
}
})
uploadTask.progress(res => {
console.log('上传进度', res.progress);
if (res.progress < 100) {
Taro.showLoading({
title: '上传中...'
})
} else {
Taro.hideLoading()
}
})
})
.catch(result => {
reject(result)
Taro.showToast({
title: "获取密钥失败!",
icon: "none",
duration: 3800
})
})
})
}
return {
uploadCDNImg
}
}