1.首先安装ali-oss
npm install ali-oss --save 或者 cnpm install ali-oss --save
2.在script中引入
import OSS from 'ali-oss';
3.直接上代码,只需要按照注释改成自己的东西,就可以直接用
<template>
<div>
//vant中上传文件
<van-uploader
:before-read="beforeRead"
accept="image/*" //这个是上传image类型的,可以自行修改
:after-read="afterRade"
/>
</div>
</template>
<script>
import OSS from 'ali-oss';
export default {
methods: {
//上传文件的前置校验,可以在里面写自己的规则,如:格式、大小等
beforeRead(){
},
//上传完成后的回调函数,此时可以上传到阿里云
afterRade(file){
let client = new OSS({
secure: true,
region: 'oss-cn-beijing', // 服务器集群地区
accessKeyId: '', // OSS帐号
accessKeySecret: '', // OSS 密码
bucket: '' // 阿里云上存储的 Bucket
})
//这个是上传图片示例,在下面存储时给路径加个type,这样返回的链接可以直接用
switch (item.file.type) {
case 'image/jpeg': {
type = 'jpeg'
}break;
case 'image/jpg': {
type = 'jpg'
}break;
case 'image/gif': {
type = 'gif'
}break;
case 'image/png': {
type = 'png'
}break;
}
//存储路径,并且给图片改成唯一名字
let key = 'fkgshops/shopid=' + this.$store.getters.shopId + '&time=' + new Date().getTime() + '&id=' + this.guidGenerator() + '.' + type
//OSS上传
return client.put(key, '你需要上传到阿里的文件流').then( res => {
//上传成功后获取阿里给你返回的链接
console.log(client.signatureUrl(key,{ expires: 999999999999999 }))
})
},
guidGenerator() {
var S4 = function() {
return ((1 + Math.random())*0X10000|0).toString(16).substring(1);
};
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
},
}
}
</script>