通过chooseImage等上传的(http...)是临时路径
1.Base64编码:
Base64编码的主要作用是在不可靠的传输媒介上安全地传输数据,比如电子邮件中的附件、网页中的图像数据(也就是说可以直接在网页打开)等。
2.示例:
<template>
<view>
message页面
<button type="primary" @click="chooseImg">上传图片</button>
<img v-for="img in imgArr" :src="img" @click="previewImg(img)">
</view>
</template>
<script>
export default {
data() {
return {
imgArr: []
}
},
methods: {
chooseImg() {
uni.chooseImage({
count: 9,
success: (res) => {
this.handleImageToBase64(res.tempFilePaths);
}
})
},
handleImageToBase64(imagePaths) {
imagePaths.forEach((path) => {
uni.getFileSystemManager().readFile({
filePath: path,
encoding: 'base64',
success: (res) => {
console.log("res",res);
this.imgArr.push('data:image/jpeg;base64,' + res
.data); // 将Base64编码的图片数据存入数组
},
fail: (error) => {
console.error('Failed to read file:', error);
}
});
});
},
previewImg(index) {
// 根据索引预览图片
uni.previewImage({
current: this.imgArr[index], // 当前预览的图片路径
urls: this.imgArr // 预览的图片数组
})
console.log("current2",this.imgArr);
}
}
}
</script>
<style scoped>
</style>
通过 handleImageToBase64
方法,用于将选择的图片转换为Base64编码数据并存放在 imgArr
数组中。在这个方法中,使用uni.getFileSystemManager().readFile
来读取图片文件并转换为 Base64 编码数据,然后将其存入数组中。这样,imgArr
数组中的数据就是Base64编码的图片数据,可以传递给后端进行进一步处理。