uniapp upload pictures to base64 code (APP end, WeChat end)

Plugin address: https://ext.dcloud.net.cn/plugin?id=123

 code:

Note that when importing, the object {} must be imported and cannot be deleted, otherwise an error will be reported: (0 , _index.default) is not a function

<template>
	<view>
		<view @click="chooseImg">拍照</view>
		<view v-if="imgList.length > 0">
			<view v-for="(item,index) in imgList" :key="index">
				<image :src="item" mode=""></image>
			</view>
		</view>
	</view>
</template>
 
<script>

	import { pathToBase64, base64ToPath } from '../../utils/image-tools/index.js'
//注意点 引入的时候 必须是对象{}引入  不可删除  否则会报错:(0 , _index.default) is not a function
	export default {
		data() {
			return {
				imgList: [],
			}
		},
		methods:{
			chooseImg(){
				let that = this;
				uni.chooseImage({
				    success: (chooseImageRes) => {
				        const tempFilePaths = chooseImageRes.tempFilePaths;
						// #ifdef MP-WEIXIN
						uni.getFileSystemManager().readFile({
							filePath: tempFilePaths[0],
							encoding: 'base64',
							success: r => { 
								console.log(r.data)
								let base64 = 'data:image/jpeg;base64,'  + r.data;
								that.imgList.push(base64)
							}
						})
						// #endif
						// #ifdef APP-PLUS
						pathToBase64(tempFilePaths[0])
						  .then(base64 => {
							that.imgList.push(base64)
						  })
						  .catch(error => {
						    console.error(error)
						  })
						// #endif
				    }
				});
			}
		}
	}
</script>
 
<style>
</style>

important point:

If it is only used in the WeChat applet, the method just uses

// #ifdef MP-WEIXIN
	uni.getFileSystemManager().readFile({
		filePath: tempFilePaths[0],
		encoding: 'base64',
		success: r => { 
		console.log(r.data)
		let base64 = 'data:image/jpeg;base64,'  + r.data;
		that.imgList.push(base64)
	}
})
// #endif

You can meet the requirements without downloading or installing plug-ins. In addition, it should be noted that this method needs to splice 'data:image/jpeg;base64,' in front of the returned base64 code, so that the image can be displayed normally.

If you need to be compatible with the app, use directly:

pathToBase64(tempFilePaths[0])
	.then(base64 => {
			that.imgList.push(base64)
	})
	.catch(error => {
			console.error(error)
})

After installing or downloading the plug-in, use it directly, you can convert the image to base64 in the app and WeChat applet at the same time. In addition, it should be noted that the base64 returned by this method has 'data:image/jpeg;base64,' so it can be directly used for image echo.

Guess you like

Origin blog.csdn.net/weixin_44285250/article/details/114584020