vue 图片上传

 Base64图片转换-- src-utils

/**
 * File转换Base64 工具
 */
export const fileToBase64 = function(file) {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.onload = function(event) {
      resolve(event.target.result);
    };
    reader.readAsDataURL(file);
  })
}

main,js中引入

import  BastUtils from './utils/BastUtils'
Vue.prototype.BaseUtils = BastUtils;

1、表单书写(只显示一个框,如果有图片,就显示上传的图片----只能放单张)

<el-form-item label="网站logo" prop="logo">
        <el-upload name="logo" action='#' class="avatar-uploader" :show-file-list="false" 
          :http-request="fileUpload" :on-success="handleAvatarSuccess" 
          style="width: 100px;height: 100px;text-align: center;margin: 0px;display: block;">
          <img :src="evelForm.logo" v-if="evelForm.logo" style="width: 100px;height: 100px;">
          <div v-else style="width:100px;height:100px;border:1px solid LightGray">
            <i class="el-icon-plus" style="width:100px;height:100px;line-height: 100px;"></i>
          </div>
        </el-upload>
      </el-form-item>

页面使用

this.BaseUtils.fileToBase64(file)

 调用上传

async fileUpload(fileInfo) {
      this.subDisabled = true  //防止图片上传较慢,多次点击定义button的 disabled属性
      let file = fileInfo.file;
      try {
        //file文件上传不要调用base64,直接上传fileInfo.file即可
        const value = await this.BaseUtils.fileToBase64(file)
        const res = await api/*接口调用*/({ icon: value })
        if (res.code == 1) {
            this.evelForm[fileInfo.filename] = res.data
        }
        this.$message({
          showClose: true,
          message: res.msg,
          type: res.code == 1 ? 'success' : 'warning'
        });
        this.$nextTick(() => {
          this.subDisabled = false
        })
      } catch (error) {
        throw new Error(error);
      }
    },

2、element-plus图片上传 方法二

<el-upload class="editor-img-uploader" :action="upLoadUrl" :show-file-list="false" :headers="headers"
      :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
      <i class="el-icon-plus editor-img-uploader"></i>
    </el-upload>


<script setup>
let upLoadUrl = ref(uploadImage);
let headers = reactive({
  token: sessionStorage.getItem("token"),
});

// 图片上传前拦截
function beforeAvatarUpload(file) {
  const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
  const isJPG = type.includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage({
      message: "图片格式错误",
      type: "success",
    });
  }
  if (!isLt2M) {
    ElMessage({
      message: "上传图片不能超过" + size.value + "M",
      type: "success",
    });
  }
  return isJPG && isLt2M;
}

// 图片上传成功返回图片地址
function handleAvatarSuccess(res, file) {
  // 上传成功
  if (res) {
    
  }
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值