最近在公司对接了一个文件上传到七牛云的项目
记录一下
sdk 下载
https://codeload.github.com/gpake/qiniu-wxapp-sdk/zip/refs/heads/master
在你页面中引入
import qiniuUploader from '../util/qiniuUploader.js'
这里用到了两个uni-app的方法
图片查看
uni.previewImage
图片选择
uni.chooseImage
由于本地页面响应速度比服务器反应快所以 创建一个数组 来存放本地图片地址
localImgList
具体实现过程是先获取到公司后台生成的 token 再使用uni-app的api获取到图片地址 本地保存一份图片本地地址 然后调用qiniuUploader.upload 上传图片 吧token 等参数带进去 上传完成后 (我这里是直接拼接地址得到上传后的图片地址)得到地址 。
//删除图片
imgDelete(id){
this.imgList.splice(id, 1)
this.localImgList.splice(id, 1)
},
// 查看图片
imgPreview(arr,index) {
uni.previewImage({
loop: true,
urls: arr,
current: index,
})
},
// 图片选择
async selectImg(){
// 这里必须同步 不然后面没有token 会导致报错
await this.qiniuToken()
let that = this;
uni.chooseImage({
count: 9 - this.localImgList.length,
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
res.tempFilePaths.forEach(item=>{
that.upimg(item)
// 本地图片添加到数组
that.localImgList.push(item)
})
}
})
},
// 上传图片
upimg(img){
// 得到图片路径
let path = 'vxCx/' + img.split('//')[1]
// 交给七牛上传
qiniuUploader.upload(img, (res) => {
this.setData({
'imageURL': res.imageURL,
});
}, (error) => {
console.log('error: ' + error);
}, {
region: 'ECN', //服务器区域号
domain: RequestConstant.QiNiu,//七牛云域名
key: path, // 上传到七牛云图片就是这路径
uptoken: this.token, // 由其他程序生成七牛 uptoken
}, (res) => {
console.log('上传进度', res.progress)
console.log('已经上传的数据长度', res.totalBytesSent)
console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
}, (res) => {
// 取消上传
}, (res) => {
// `before` 上传前执行的操作
}, (err) => {
// `complete` 上传接受后执行的操作(无论成功还是失败都执行)
});
// 得到上传后的图片 拼接地址收集
this.imgList.push(RequestConstant.QiNiu+'/'+path)
},
// 获取七牛token
qiniuToken(){
this.$get(RequestConstant.qiniuToken).then(res=>{
this.token = res.result
})
},