微信小程序七牛云插件 下载
// import { uploadCompanyFilePolicy, uploadFilePolicy } from '@/api/common'
const qiniuUploader = require('../../tool/qiniu-wxapp-sdk.js')
import fetch from '@/api/apiTool.js'
import VODUpload from '@/tool/aliyun-upload-sdk-1.0.1.min'
import { getUploadTiket, getTagType, getTag, pushArtice, saveEditContent, circleDetail, getVideoUpload } from './api/good'
//初始化七牛云配置
function initQiniu(uptoken) {
var options = {
region: 'NEW',
qiniuUploadToken: uptoken,
uptokenURL: null,
// uptokenFunc 这个属性的值可以是一个用来生成uptoken的函数,详情请见 README.md
uptokenFunc: function () {
return uptoken
},
shouldUseQiniuFileName: true,
}
// 将七牛云相关配置初始化进本sdk
qiniuUploader.init(options)
}
//上传图片
uploadMedia() {
if (!this.$store.state.token) {
this.$store.commit('changeLoginModule', true)
return
}
if (this.fileList.length === 15) {
uni.showToast({
icon: 'none',
title: '最多支持上传15个媒体文件',
})
return
}
uni.chooseMedia({
mediaType: ['image'],
count: 9,
success: res => {
const { tempFiles } = res
this.uploadTool(tempFiles, res => {
//上传成功的回调函数
console.log('-------')
console.log(res)
if (res.code === '000000') {
const { fileUrl, id } = res.data
this.fileList.push({
fileUrl,
id,
type: 1,
})
}
})
},
})
},
uploadTool: async function (filePath, callback) {
uni.showLoading({
title: '正在获取凭证',
})
const { data } = await getUploadTiket()
//获取凭证的请求接口
uni.hideLoading()
console.log(data)
if (data.code === '000000') {
initQiniu(data.data.policy)
} else {
return
}
const upload = file => {
return new Promise((resolve, reject) => {
qiniuUploader.upload(
file,
res => {
console.log('提示: wx.chooseImage 目前微信官方尚未开放获取原图片名功能(2020.4.22)')
resolve(res)
uni.hideLoading()
},
error => {
reject(error)
console.error('error: ' + JSON.stringify(error))
uni.showToast({
title: 'error: ' + JSON.stringify(error),
duration: 2000,
icon: 'none',
})
uni.hideLoading()
},
{ uptoken: data.data.policy, region: 'NEW' },
progress => {
console.log('上传进度', progress.progress)
console.log('已经上传的数据长度', progress.totalBytesSent)
console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
}
)
})
}
filePath.forEach(async v => {
uni.showLoading({
title: '正在上传文件',
})
const res = await upload(v.tempFilePath)
callback && callback(res)
})
},
需要去小程序里面配置一下上传的地址,其余的上传进度,上传前后的回调方法要去看文档了,我这里只做简单的上传头像而已
注意一个问题
请求七牛云上传的token,最好是放在获取图片成功后的回调里面,如果放在前面获取,选图片后会触发onHide onShow等生命周期,可能会出现问题,我这里放在前面执行上传的凭证就消失没了
注意qiniuUploader.upload的第四个参数是option 需要配置一下上传前置操作,更新tiket,避免过期