一、安装
npm install ali-oss --save
二、引入
import OSS from 'ali-oss'
三、实例化OSS:
默认上传根路径为 bucket表示的目录
let ossClient = new OSS({
region: "oss-cn-xxxxxxx",
accessKeyId: "xxxxxxxxxxxxxxxx",
accessKeySecret: "xxxxxxxxxxxxxxxx",
bucket: "xx-xxxxxxxx"
});
四、在定义上传方法:
在上传文件之前添加路径
/operationsystem/test/upload/image/chainadmin/+file.name
在oss客户端上可以看到,表示将文件上传到指定的目录下。
function uploadoss(callback, { file }) {
let ossClient = new OSS({
region: "xxxxxxxxx",
accessKeyId: "xxxxxxxxxxxxxxxx",
accessKeySecret: "xxxxxxxxxxxxxxxxxxxxxx",
bucket: "xxxxxxxxxxxx"
});
let path = '/operationsystem/test/upload/image/chainadmin/';
let endtype = file.name.substring(file.name.lastIndexOf('.'));
let name = file.name.substring(0, file.name.lastIndexOf('.')) + new Date().toString();
let fileName = path + name + endtype;
let loadingInstance = Loading.service({ fullscreen: true, background: "rgba(25,25,25,0.5)" });
ossClient.put(fileName, file, {
// 'ContentType': 'image/jpeg'
}).then(({ res, url, name }) => {
loadingInstance.close();
if (res && res.status == 200) {
console.log(`阿里云OSS上传图片成功回调`, res, url, name );
return callback( res, url, name )
}
}).catch((err) => {
loadingInstance.close();
Message({
'message': '上传失败',
'type': 'error'
})
console.log(`阿里云OSS上传图片失败回调`, err);
});
}
五、调用上传方法
uploadoss((res,url,name)=>{
//url为上传成功文件地址 https://xxxxxxxxxx
//name为上传成功文件名字
do something....
},{file})
let tempFilePaths = '';
let host = "https://xxxxx-xxxxxx.oss-cn-xxxxxxx.aliyuncs.com/";
wx.chooseImage({//通过相册选择照片
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success (res) {
tempFilePaths = res.tempFilePaths[0]
})
let imagename = tempFilePaths.substring(tempFilePaths.lastIndexOf('/')+1);//截取文件名字
let path = "wechat/test/image/"+ imagename; //自定义路径:wechat/test/image/xxx.png
wx.uploadFile({
url: host, //ali-oss上传地址
filePath: tempFilePaths,
header: {
"Content-Type": "multipart/form-data",
},
name: 'file',
method: 'post',
formData: { //HTTP 请求中其他额外的 form data
"key": path, //上传图片的名字和路径(默认路径为根目录。自定义路径:xxx/xxx.png)
"policy": xxxxxxxxx,
"OSSAccessKeyId": xxxxxxxxxxxx,
"signature": xxxxxxxxxxxxxxxx,
"success_action_status": "200",
},
success: function(res) {
if (res.statusCode == "200") {
console.log("阿里云OSS上传图片成功"+host+path)
}
},
fail: function(res) {
wx.showToast({
title: "上传失败",
icon: 'none',
})
}
});
policy,OSSAccessKeyId,signature,有关签名的获取和原理,请参考官方文档如下:
https://help.aliyun.com/document_detail/31926.html