uniapp小程序图片直传阿里云oss结合uni-file-picker插件
目录
uniapp小程序图片直传阿里云oss(结合uni-file-picker插件)
需求:uniapp开发的微信小程序,使用 uni-file-picker 插件可以将图片上传至当前绑定的dcloud服务空间,而我们需要将图片直接传到公司的阿里云空间,不使用dcloud服务空间,不用走后台接口即可上传。
由于一开始做图片上传选用了uni-file-picker插件,后更改需求直传阿里云,所以这里是结合uni-file-picker插件做的图片直传。
- uni-file-picker插件使用
<!--
@readonly 组件是否只读
@fileMediatype 上传类型,支持image/video
-->
<uni-file-picker
class="imgItem"
:readonly="type == 'view'? true: false"
v-model="compressStart"
fileMediatype="image"
mode="grid"
:limit="1"
@select="selectImg($event)"
@delete="delImg($event)"
>
</uni-file-picker>
- 下载uniapp的阿里云oss上传工具插件,
引入sdk包
// 你的sdk包文件路径
import uploadImage from "../../js_sdk/yushijie-ossutil/ossutil/uploadFile.js"
- 修改sdk包中 config.js 文件配置信息
var fileHost = 'https://msmk-vms-images.oss-cn-beijing.aliyuncs.com/';//你的阿里云地址最后面跟上一个/ 在你当前小程序的后台的uploadFile 合法域名也要配上这个域名
var config = {
//aliyun OSS config
uploadImageUrl: `${fileHost}`, // 默认存在根目录,可根据需求改
AccessKeySecret: '你的阿里云key', // AccessKeySecret 去你的阿里云上控制台上找
OSSAccessKeyId: '你的阿里云keyid', // AccessKeyId 去你的阿里云上控制台上找
timeout: 87600 //这个是上传文件时Policy的失效时间
};
module.exports = config
- 选择图片并上传
/**
* @description 上传至阿里云
* {imgFileName} 阿里云保存图片的文件夹名,自定
*/
selectImg(e,type) {
console.log('选择图片成功',e)
console.log('图片类型',type)
let filearr = e.tempFiles
// 支持多图片上传
for(var i=0;i<filearr.length;i++) {
let file = filearr[i].path
uploadImage(file, 'imgFileName/',
result => {
//成功之后,可以将result带去执行其它方法或者赋值
console.log('success',JSON.stringify(result));
// 保存上传后的图片地址
this.imgArr.push(result)
},result =>{
//这里写上传失败的代码
uni.showToast({
title: '上传图片至阿里云失败',
icon: 'none'
})
console.log('fail',JSON.stringify(result));
})
}
}