温馨提示  2024年 6月我们已经停止开发者板块文章内容更新,谢谢来访。存档数据
前端 2024-04-07 31 次阅读

uniapp、vue、小程序、js图片转base64 示例代码

一般来说uniapp就是用的JS, 所以可以使用JavaScript将图片转换为base64编码。Base64编码是一种将二进制数据转换为可见字符的编码方式,可以将图片以文本方式存储或传输。下面是一个示例代码,演示如何在uniapp中使用Vue.js和JavaScript将图片转换为base64编码:

<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="convertToBase64">转换为Base64</button>
    <img :src="imageUrl" alt="转换后的图片" />
  </div>
</template>
<script>
export default {
  data() {
    return {
      imageUrl: '',
      file: null
    };
  },
  methods: {
    handleFileChange(e) {
      this.file = e.target.files[0];
    },
    convertToBase64() {
      if (this.file) {
        const reader = new FileReader();
        reader.readAsDataURL(this.file);
        reader.onload = (e) => {
          this.imageUrl = e.target.result;
        };
      }
    }
  }
};
</script>