当前位置:   article > 正文

element-ui实现证件照上传预览下载组件封装

element-ui实现证件照上传预览下载组件封装

element-ui实现证件照上传预览下载组件封装

效果:

element ui 实现证件的上传下载预览功能

参数说明

我只写了两个参数,后续有需求再对其组件进行丰富~

参数说明
fileListProp用来存储上传后后端返回的图片UR了
uploadUrl图片上传反悔的URL后端接口地址

父组件调用:

 <au-upload :uploadUrl="'http://192.168.60.27:8888/file-storage-center/object/uploadObjectByMultipartFile'" :fileListProp="fileList1">
 </au-upload>
 <p><span>*</span> <span class="idCardTip">身份证国徽面</span></p>

  • 1
  • 2
  • 3
  • 4

组件源码:

<template>
  <div>
    <el-upload v-loading="loading" element-loading-text="上传中..." :style="{ 'width': width + 'px', 'height': height + 'px' }" class="avatar-uploader"
      :class="noneBtnDealImg ? 'disUoloadSty' : ''" ref="uploader" 
      :file-list="fileList" 
      :action="uploadUrl"
      :before-upload="beforeUpload" 
      :on-exceed="(files, fileList) => handleExceed(files, fileList, 1)"
      :on-change="(file, fileList) => this.handleAvatarSuccess(file, fileList)"
      list-type="picture-card"
      :auto-upload="true">
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
            <i class="el-icon-download"></i>
          </span>
          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import axios from 'axios'; // 导入axios
export default {
  props: {
    fileListProp: {
      typeof: Array,
      default: () => []
    },
    uploadUrl: {
      typeof: String,
      default: () => ''
    },
  },
  data() {
    return {
      width: 140,
      height: 140,
      fileList: this.fileListProp,
      headerObj: {
        authorization: getToken(),
        tenant_id: 0,
      },
      img: '',
      noneBtnDealImg: false,
      uploadfileurl: this.uploadFileURL,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      loading: false,
    };
  },
  created() {
  },
  mounted() {
    this.noneBtnDealImg = this.fileList.length >= 1
  },
  methods: {
    beforeUpload(file) {
      // 检查文件类型、大小等
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGorPNG) {
        this.$message.error('上传的图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传的图片大小不能超过 2MB!');
        return false;
      }
      // 发起上传请求
      this.directUpload(file);

      // 返回false阻止el-upload组件的默认上传行为
      return false;
    },
    async directUpload(file) {
      try {
        this.loading = true
        const formData = new FormData();
        formData.append('file', file);
        const response = await axios.post(this.uploadUrl, formData, {
          headers: this.headerObj,
        });
        // 处理上传成功
        this.handleUploadResponse(response.data, file);
      } catch (error) {
        // 处理上传错误
        console.error('Upload error:', error);
      } finally {
        this.loading = false;
      }
    },
    handleUploadResponse(responseData, file) {
      // 根据后端返回的数据,更新fileList
      const updatedFile = {
        ...file,
        response: responseData,
        url: responseData.data || '', // 假设后端返回的URL在这里
      };
      this.fileList.push(updatedFile);
      //当前只保留一张照片
      this.$nextTick(() => {
        if (this.fileList.length >= 1) {
          const uploadBox1 = document.getElementsByClassName('avatar-uploader');
          uploadBox1[0].style.height = this.height + "px"
        }
        this.noneBtnDealImg = this.fileList.length >= 1
      })
    },
    //图片删除
    handleRemove(file, fileList, name) {
      const index = this.fileList.indexOf(file);
      if (index > -1) {
        this.fileList.splice(index, 1);
      }
      this.img = ''
      this.noneBtnDealImg = this.fileList.length >= 1
      this.$refs['uploader'].clearFiles();
      this.$forceUpdate()
    },
    handleExceed(files, fileList, num) {
      this.$message.warning(`当前限制选择 ${num} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleAvatarSuccess(file, fileList) {
      this.$nextTick(() => {
        if (fileList.length >= 1) {
          const uploadBox1 = document.getElementsByClassName('avatar-uploader');
          uploadBox1[0].style.height = this.height + "px"
        }
        this.noneBtnDealImg = fileList.length >= 1
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      // 获取图片的真实URL
      const imageUrl = file.response && file.response.data ? file.response.data : file.url;
      // 创建一个隐藏的可下载链接
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = imageUrl;
      link.download = file.name || 'image.png'; // 设置下载的文件名,如果没有name属性则默认为'image.png'
      // 触发点击事件以下载图片
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
}
</script>

<style scoped>
.el-form-item__label::after {
  content: '(最多1张)';
  display: block;
  font-size: 12px;
  color: #999;
  line-height: 12px;
}

/deep/ .allUpload .el-form-item__content {
  display: flex;
}

/deep/ .el-upload-list__item {
  transition: none !important
}

/deep/ .disUoloadSty .el-upload--picture-card {
  /* 上传按钮隐藏 */
  display: none !important;
}

/deep/ .el-upload--picture-card {
  width: 140px;
  height: 140px;
}

/deep/ .el-upload-list--picture-card .el-upload-list__item {
  margin-right: 0px !important;
  margin-bottom: 0px !important;
}

/deep/ .el-upload-list__item {
  width: 140px !important;
  height: 140px !important;
}

/deep/ .el-upload-list__item div:nth-child(1) {
  width: 100% !important;
  height: 100% !important;
}
/deep/ .el-loading-spinner .el-loading-text{
  text-align: center;
  margin-top: -18px;
}
</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/289970
推荐阅读