[Uniapp开发日记]上传图片( 超级详细、云开发 、简单易懂 、CV即用 )

官方文档

说实话,uniapp 的官方文档有点小乱
找不到,可以参考一下下图
请在阅读此教程前,一定一定一定要大概看看官方文档
然后结合进行使用
在这里插入图片描述

内置云存储概述:

  1. web界面:即在https://unicloud.dcloud.net.cn/ web控制台,点击云存储,通过web界面进行文件上传。该管理界面同时提供了资源浏览、删除等操作界面。
  2. 客户端API或组件上传:在前端js中编写uniCloud.uploadFile,或者使用uni ui的FilePicker组件,文件选择+上传均封装完毕。
  3. 云函数上传文件到云存储:即在云函数js中编写uniCloud.uploadFile

详细实现过程
通过 chooseImage 选择图片并且success返回的参数中tempFiles为图片的本地文件列表,每一项都是一个File对象
chooseImage官方文档

						uni.chooseImage({					
						success:async res=>{
						uni.showLoading({
							title:"上传中请稍后",
							mask:true
						})
						// 打印  这里关注一下 tempFiles 中 
						console.log(res)
						console.log(res.tempFilePaths)

在这里插入图片描述
tempFilePaths: 路径数组
tempFiles: File 数组对象, 里面包含有 各种属性
在这里插入图片描述

下面重点讲一下云存储客户端 API

函数名: uploadFile(Object object)
在这里插入图片描述
响应参数

简单来说: fileID就是上传图片后,云服务器返回的链接
requestId 就是用来排查错误的 成功 or 失败

在这里插入图片描述

  					let res= await uniCloud.uploadFile({
  						filePath:item.path,       //  本地临时路径  
  						cloudPath:item.name || randomName   // 名字
  					})

通过循环实现多张图片上传

						for (let item of res.tempFiles) {
							// 获取文件后缀名
							let suffix = item.path.substring(item.path.lastIndexOf("."));
							let randomName=Date.now() + "" + String( Math.random() ).substr(3,6)+suffix
							// 异步同步化 
							let res= await uniCloud.uploadFile({
								filePath:item.path,    
								cloudPath:item.name || randomName
							})
							// 这里使用 云存储函数 uploadFile 
							// res 返回值: fileID: 文件唯一 , 用来访问文件, 建议存储起来
							//requestId: 请求序列号, 用于错误排查
							// 富文本插入图片 如果没有富文本的话,下面这部分需要删除
							this.editorCtx.insertImage({
								src:res.fileID
							})							
						}
						uni.hideLoading()
						}

完整code

clickInsertImage(){
				uni.chooseImage({					
					success:async res=>{
						uni.showLoading({
							title:"上传中请稍后",
							mask:true
						})
						// 打印  这里关注一下 tempFiles 中 
						console.log(res)
						console.log(res.tempFilePaths)
						
						for (let item of res.tempFiles) {
							// 获取文件后缀名
							let suffix = item.path.substring(item.path.lastIndexOf("."));
							let randomName=Date.now() + "" + String( Math.random() ).substr(3,6)+suffix
							// 异步同步化 
							let res= await uniCloud.uploadFile({
								filePath:item.path,
								cloudPath:item.name || randomName
							})
							// 这里使用 云存储函数 uploadFile 
							// res 返回值: fileID: 文件唯一 , 用来访问文件, 建议存储起来
							//requestId: 请求序列号, 用于错误排查
							// this.editorCtx.insertImage({
							//	src:res.fileID
							// })							
						}
						uni.hideLoading()
					}
				})
			},
  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值