使用element中的Upload 上传进行总结

kbk在之前项目项目里面没有做过upload上传之后回显的操作,这不总结一下,以防忘记
是el-upload
当前仅支持一个图片回显,要是多个,还需要自行处理一下,转换成数组

图片上传组件 ImageUpload.vue


<template>
  <div>
    <el-upload multiple :action="uploadImgUrl" list-type="picture" :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" :limit="limit"
      :on-error="handleUploadError" :on-exceed="handleExceed" ref="imageUpload" :on-remove="handleDelete" :show-file-list="true" :headers="headers"
      :file-list="fileList" :class="{hide: this.fileList.length >= this.limit}">
      <el-button size="small" type="primary" >点击上传</el-button>
    </el-upload>

    <!-- 上传提示 -->
    <div slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>
  </div>
</template>

<script>
import { getPicture, deletePicture } from '@/api/public'
export default {
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogVisible: false,
      hideUpload: false,
      uploadImgUrl: process.env.VUE_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + token, // token请自行添加
      },
      fileList: []
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          getPicture({ fileName: val }).then(res => {
            this.fileList.push({ name: val, url: res.data })
            return
          })
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 上传前判断上传 图片格式 和 图片大小 加载
    handleBeforeUpload(file) {
      const suffix = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!suffix) {
        this.$message.error("图片只能上传jpg/png文件!");
      }
      if (!isLt5M) {
        this.$message.error("上传图片大小不能超过 5MB!");
      }
      this.number++;
      return suffix && isLt5M;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit}!`);
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.data.name, url: res.data.downFileName });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除图片
    handleDelete(file) {
      if (file.hasOwnProperty('response')) {
        deletePicture([file.response.data.downFileName]).then(res => {
          const { data } = res
          this.$modal.msgSuccess(data.msg)
        })
      }
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit("input", this.listToString(this.fileList));
      }
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败,请重试");
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, "") + separator;
        }
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>


父组件 index.vue


<template>
  <div class="teamADD" id="teamADD">
     <el-form ref="ruleForm" :model="ruleForm" label-width="100px" label-position="right" :rules="rules">
       <el-form-item label="驾驶证" prop="driverLicenseUrl">
          <ImageUpload @input="handleUpload" v-if="!disabledVal" :limit=1 :value="driverLicenseUrlOpt"></ImageUpload>
          <el-image v-if="disabledVal && !showIMGVisible" style="width: 35%; height: 75px" :src="srcIMG[0]"  :preview-src-list="srcIMG"/>
          <span v-if="disabledVal && showIMGVisible"></span>
       </el-form-item>
    </el-form>
  </div>
</template>

<script>
import ImageUpload  from '../ImageUpload'
import { getPicture, addInfo, updateInfo } from '@/api/public'
export default {
  name: "Dialog",
  data() {
    return {
      driverLicenseUrlOpt: '',
      ruleForm: {
        driverLicenseUrl: ""
      },
      // 表单校验
      rules: {
        driverLicenseUrl: [
          { required: true, message: '驾驶证不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  props: {
    title: String,
    disabledVal: Boolean,
    AddForm: Object,
   },
  created() {
    if (this.title === "详细") {
      if(this.AddForm.driverLicenseUrl === null) {
        this.showIMGVisible = true
        this.srcIMG = []
      } else {
        getPicture({ fileName: this.AddForm.driverLicenseUrl}).then(res => {
          this.srcIMG = [res.data]
        })
       }
      }
    if (this.title === "编辑" || this.title === "详细") {
      this.ruleForm = this.AddForm
      this.driverLicenseUrlOpt = this.AddForm.driverLicenseUrl
    }
  },
  methods: {
    handleUpload(val) {
      this.ruleForm.driverLicenseUrl = val
    },
    /** 提交按钮 */
    submitForm(value) {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.title === "编辑") {
            updateInfo(this.ruleForm).then((response) => {
              this.$message.success("编辑成功")
            });
          } else if (this.title === "添加") {
            addInfo(this.ruleForm).then((response) => {
             this.$message.success("添加成功")
            });
          } else {
            this.$message.success("查看成功")
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>



ending…

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值