微信小程序七牛云 图片(文件)上传预览

本文介绍如何使用七牛云SDK进行文件上传操作,包括获取token、选择及预览图片、上传图片到服务器等步骤,并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在公司对接了一个文件上传到七牛云的项目

记录一下

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
				})
			},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值