OSS upload
My Code
指定oss目录地址 文件路径拼接
代码所示 storeAs 字段拼接的 OssBox.path 为后台返回指定的文件存储路径
在需要执行上传操作的地方 执行 UploadOss(file,oss) 即可
async updataAvator() {
var timetamp = new Date().getTime();
let OssBox = await Global.GetOssKey();//全局配置的获取OSSkey的后台接口请求方法
if(!OssBox) return uni.showToast({title:"获取OSS服务失败",icon:"none",duration:1500})
let that = this;
uni.chooseImage({
count:1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], //从相册选择
success:async function(res) {
that.ImageSrc = res.tempFilePaths[0];//图片文件信息 blod
let pos = that.ImageSrc.lastIndexOf('.');
let filename = that.ImageSrc.substring(0, pos) // 文件名
let extendName = that.ImageSrc.substring(pos + 1); // 扩展名
let stroeAs = OssBox.path + timetamp + random_string(5);
//定义文件数据 + OSSkey的参数信息
let FileBox = {
"filePath":that.ImageSrc,
"formDataKey":stroeAs
}
that.FileBox = FileBox;
that.OssBox = OssBox;
// UploadOss 全局的上传文件资源的方法 返回上传后的地址 or false
// let Avatarurl = await Global.UploadOss(FileBox,OssBox);
},
fail(){
// uni.showToast({title: '取消选择图片',icon: 'none',duration: 2000});
}
});
},
//随机数 定义文件存储名称
function random_string(len) {
len = len || 32;
var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
var maxPos = chars.length;
var pwd = '';
for (let i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
APP.VUE
OSS upload
// WEB OSS直传
async UploadOss(FileBox,OssBox){
return new Promise(function(resolve, reject) {
uni.showLoading({title:"图片上传中",mask:true})
uni.uploadFile({
url: OssBox.host,
filePath: FileBox.filePath,
fileType: 'image',
name: 'file',
formData: {
'key': FileBox.formDataKey,
'policy': OssBox.policy,
'OSSAccessKeyId': OssBox.OSSAccessKeyId,
'success_action_status': '200', //让服务端返回200,不然,默认会返回204
'signature': OssBox.signature,
},
success(res) {
uni.hideLoading();
let url = OssBox.host + '/' + FileBox.formDataKey;
return resolve(url)
},
fail(err) {
uni.hideLoading();
return resolve(false)
}
})
})
}