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

时间:2019-09-05
本文章向大家介绍使用element的upload组件实现上传图片功能,主要包括使用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

原文地址:https://www.cnblogs.com/caoxueying2018/p/11465913.html