vue封装文件上传组件

2023-12-25 11:25:11

场景:为了安全起见,文件上传需要转为base64格式进行上传。
实现这样的效果。
如图
如图

1、封装uploadFile.vue组件

<template>
  <div class="upload-BOX">
    <el-upload
      class="avatar-uploader"
      action="#"
      ref="upload"
      :show-file-list="false"
      :http-request="httpRequestImg"
      :on-change="changeData"
      :on-success="handleSuccess"
      style="width: 200px; display: inline-block"
    >
      <img
        v-if="addlistPic"
        :src="'data:image/jpg;base64,' + Base64File"
        class="avatar"
        :style="{ width: imgWidth , height: imgHeight }"
      />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <p v-show="showTip">建议图片大小{{ mywidth }}*{{ myheight }},文件大小不超过{{ mysize }}kb </p>
  </div>
</template>

<script>

import mixin from "../../api/uploadFile/uploadFile";
export default {
  mixins: [mixin],
  name: "infoCard",
  props: {
    imgWidth:{
      type: String,
      default: '80px',
    },
    imgHeight:{
      type: String,
      default: '80px',
    },
    mywidth: {
      type: String,
      default: '200',
    },
    myheight: {
      type: String,
      default: '200',
    },
    mysize:{
      type: String,
      default: '200',
    },
    showTip: {
      type: Boolean,
      default: false,
    },
    listPic: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      addlistPic: this.listPic,
      Base64File: "",
    };
  },
  watch: {
    listPic: {
      handler(newVal, oldVal) {
        this.addlistPic = newVal;
        if (this.addlistPic) {
          this.getFileFn();
        }
      },
      deep: true,
      immediate: true,
    },
  },

  mounted() {},
  methods: {
    getFileFn() {
      var json = {
        id: this.listPic,
      };
      this.getFile(json).then((res) => {
        this.Base64File = res.file;
      });
    },
    changeData(file) {},
    handleSuccess(data) {},
    // 覆盖默认的上传行为,可以自定义上传的实现
    httpRequestImg(data) {
      const isJPG = data.file.type === "image/jpeg";
      const isPNG = data.file.type === "image/png";
      const isLt2M = data.file.size / 1024 / 1024 < 10;

      if (!isJPG && !isPNG) {
        this.$message.error("上传logo图片只能是 JPG 格式或者 PNG 格式!");
        return;
      }
      if (!isLt2M) {
        this.$message.error("上传logo图片大小不能超过 10MB!");
        return;
      }
      // 转base64
      this.getBase64(data.file).then((resBase64) => {
        this.Base64File = resBase64.split(",")[1];
        // this.addlistPic = this.Base64File;
        let json = {
          file: this.Base64File,
          fileName: data.file.name,
          fileExt: data.file.type,
        };
        this.uploadImg(json).then((res) => {
          this.$message.success("上传成功");
          this.addlistPic = res.body.id;   //后端返回一个图片id作为标识,表单提交时传参
          this.$emit("uploadSuccess", res.body.id);
        });
      });
    },

    // 转base64编码
    getBase64(file) {
      this.dialogVisible = false;
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let fileResult = "";
        reader.readAsDataURL(file); //开始转
        reader.onload = function () {
          fileResult = reader.result;
        };
        //转失败
        reader.onerror = function (error) {
          reject(error);
        };
        //转结束 resolve 出去
        reader.onloadend = function () {
          resolve(fileResult);
        };
      });
    },
  },
};
</script>

<style scoped lang="scss">
/deep/ .el-upload--text {
  width: 80px;
  height: 80px;
  line-height: 80px;
  font-size: 24px;
}
.avatar {
  width: 80px;
  height: 80px;
  /* display: block; */
}
</style>

2、组件调用

html代码

<upload-file
	:listPic="formData.cornerImg"
	@uploadSuccess="getUploadData4"
	:showTip="false"
	:mywidth="'200'"
	:myheight="'200'"
	:mysize="'200'"
	:imgWidth="'60px'"
	:imgHeight="'60px'"
></upload-file>

js代码

import uploadFile from "../../components/uploadFile/uploadFile.vue";
components: {
			uploadFile,
		},
//data中定义的数据
formData: {
  cornerImg: "",
}

//methods方法
getUploadData4(data) {
      this.formData.cornerImg = data;
},	

文章来源:https://blog.csdn.net/weixin_38483133/article/details/135192227
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。