怪味曹小豆

导航

使用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

 

posted on 2019-09-05 14:43  怪味曹小豆  阅读(2116)  评论(0编辑  收藏  举报