Vue实现上传图片转base64编码(案例详细步骤)

我们在写后台管理系统的时候,有时候需要上传图片,那么就要用到upload组件,刚好最近写项目遇到,记录一下

效果展示

在这里插入图片描述
点击按钮然后选择电脑里的图片,下面列表会进行图片的预览展示,提交表单便会提交图片的信息(通常是将图片转换成base64编码存入数据库中)

实现步骤

<el-upload
  list-type="picture"
   action=''
   accept=".jpg, .png"
   :limit="1"
   :auto-upload="false"
   :file-list="fileList"
   :on-change="getFile"
   :on-preview="handlePictureCardPreview"
   :on-remove="handleUploadRemove"
   >
	<el-button size="small" type="primary" @click="uploadimg">选择图片上传</el-button>
	<div slot="tip" class="el-upload__tip">只能上传一张jpg/png文件</div>
</el-upload>

参数说明:
list-type: 文件列表的类型
action: 必选参数,上传的地址
accept:接受上传的文件类型,这里是jpg和png
limit:最大允许上传的个数
auto-upload:是否在选取文件后立即进行上传,这里记得填 false
file-list:上传的文件列表
on-change:文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
on-preview:点击文件列表中已上传的文件时的钩子。
on-remove:文件列表移除文件时的钩子
js部分:
通过getFile方法获取文件信息

getFile(file, fileList) {
  this.getBase64(file.raw).then(res => {
    const params = res
    this.proofImage = params
  })
},

图片转base64编码:

getBase64(file) {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader()
    let imgResult = ''
    reader.readAsDataURL(file)
    reader.onload = function () {
      imgResult = reader.result
    }
    reader.onerror = function (error) {
      reject(error)
    }
    reader.onloadend = function () {
      resolve(imgResult)
    }
  })
},

预览和删除

handleUploadRemove(file, fileList) {
  this.proofImage = ''
  this.ruleForm.message_img = ''
},
handlePictureCardPreview(file) {
  console.log(this.proofImage)
},

关于upload的更多相关属性,移步官方文档自行查看 点我跳转

猜你喜欢

转载自blog.csdn.net/weixin_45745641/article/details/120851834