uniapp 选择文件并转为base64

uniapp yekong 2247℃

uniapp因为接口接收的是base64而非文件路径,所以需要的是将文件转为base64。
首先需要安装一个依赖

安装依赖image-tools

npm i image-tools --save

引用

import { pathToBase64, base64ToPath } from 'image-tools'

使用

// 选择图片
			imgSelect(){
				uni.chooseImage({
				    count:1, //默认9
				    sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有
				    sourceType: ['album'], //从相册选择
				    success:(res)=>{
				        // console.log(JSON.stringify('测试',res));
						console.log('测试',res.tempFilePaths[0]);
                         //赋值用于显示图片
						this.checkedImg = res.tempFilePaths[0]
						// 调用转换方法
						this.imgToBase64(res.tempFilePaths[0]).then(base64=>{
							this.iconBase64 = base64
											console.log("[转换成base64]",base64)
									})
				    }
				});
			},
 
 
//把图片转换成base64
			imgToBase64(data){
				return new Promise((resolve,reject)=>{
						pathToBase64(data).then(base64 => {
							resolve(base64)
						 }).catch(error => {
							console.error(error)
							reject(error)
						})		
				})			
			},

转自:使用uni-app中的uni.chooseImage选中的图片且转换为base64格式。

喜欢 (1)