一、需求:
做一個背景圖上傳插件,並且將獲取到的文件流轉換為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>
