图片上传

form表单内包含图片上传,且需要用formData传值

上传组件封装

<template>
  <div class="upload-img">
    <img :src="imageSrc" v-if="imageSrc" class="img">
    <div class="upload-btn" v-if="!imageSrc">
      <i class="el-icon-plus add-icon"></i>
    </div>
    <input type="file" id="up-file" class="up-file" @change="onUpload" title=" ">
  </div>
</template>


<script>
export default {
  props: {
    imageSrc: {
      type: String,
      default: ""
    }
  },
  methods: {
    onUpload(e) {
      const _this = this
      let fileContent = e.target.files[0];
      const isJPG =
        fileContent.type === "image/jpeg" || fileContent.type === "image/png";
      const isLt2M = fileContent.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$notify({
          title: this.$t('common.ImgFormTip'),
          type: 'success'
        });
        return;
      }
      if (!isLt2M) {
        _this.$messgae({
          type: 'warning',
          message: this.$t('common.ImgSizeTip')
        })
        return;
      }
      if (!fileContent) {
        return;
      }
      let formData = new FormData();
      console.info(fileContent)
      formData.append("image_src", fileContent);
      let that = e.target;
      let fr = new FileReader(); //初始化
      let upImg = "";
      fr.readAsDataURL(fileContent); //选择文件中的头一个开始读取,将img读取为base64编码可以被img直接解析
      fr.onload = e => {
        //在filereader中读取完毕开始异步加载
        upImg = e.target.result; //图片src路径
        that.value = null; //解决change事件重复选择同一文件是不能重新渲染载入事件
        let res = {
          upImg: upImg,
          fileContent: fileContent
        };
        this.$emit("emitSuccess", res);
      };
    }
  }
};
</script>

<style lang="less" scoped>
.upload-img {
  width: 100px;
  height: 100px;
  position: relative;
}
.up-file {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 100;
  opacity: 0;
  cursor: pointer;
}
.upload-btn {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
.add-icon {
  font-size: 30px;
  color: #8c939d;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>

组件使用

父组件

<upload-img :imageSrc="initDoctor.avatar" @emitSuccess="onUploadSuccess"></upload-img>


onUploadSuccess(res) {
 this.initDoctor.avatar = res.upImg
 this.doctorFormData.append("avatar", res.fileContent);
 this.$forceUpdate()
},

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值