使用element的upload组件实现上传图片功能


一、需求:

做一个背景图上传插件,并且将获取到的文件流转换为base64编码。

二、实现方案:

  • 使用element组件库的upload组件
  • 使用FileReader构造函数将文件流转换为base64编码

三:代码:

<template>
  <div>
    <el-upload action="#" :file-list="fileList" :before-upload="changeToBase64"></el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [
        {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'},
        {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}
      ]
    }
  },
  methods: {
    changeToBase64(file) {
      // console.log(file);
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function(e) {
        console.log(this.result); //this.result即为文件流的base64编码
      }
    }
  }
}
</script>

<style>

</style>
View Code

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM