vue封装文件上传组件

场景:为了安全起见,文件上传需要转为base64格式进行上传。

实现这样的效果。

如图

1、封装uploadFile.vue组件

javascript 复制代码
<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代码

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

js代码

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

//methods方法
getUploadData4(data) {
      this.formData.cornerImg = data;
},	
相关推荐
极梦网络无忧1 分钟前
基于 Vite + Vue3 的组件自动注册功能
前端·javascript·vue.js
Predestination王瀞潞14 分钟前
5.4.3 通信->WWW万维网内容访问标准(W3C):WWW(World Wide Web) 协议架构(分层)
前端·网络·网络协议·架构·www
爱学习的程序媛24 分钟前
【Web前端】优化Core Web Vitals提升用户体验
前端·ui·web·ux·用户体验
zabr25 分钟前
花了 100+ 篇笔记,我整理出 了一套 AI Agent 工程完全指南
前端·后端·agent
软弹37 分钟前
深入理解 React Ref 机制:useRef 与 forwardRef 的协作原理
前端·javascript·react.js
YaHuiLiang41 分钟前
Ai Coding浪潮下的前端:“AI在左,裁员在右”
前端
雪碧聊技术1 小时前
前端vue代码架子搭建
前端·javascript·vue.js·前端项目代码框架搭建
爱学习的程序媛1 小时前
【Web前端】前端用户体验优化全攻略
前端·ui·交互·web·ux·用户体验
han_1 小时前
JavaScript设计模式(二):策略模式实现与应用
前端·javascript·设计模式
x***r1511 小时前
Notepad++ 8.6 安装教程:详细步骤+自定义安装路径(附注意事项)
linux·前端·javascript