el-upload批量图片上传封装

发布时间 2023-03-29 17:30:05作者: 倍姬存希

需求:

实现图片一次性上传

 

 调一次接口

 

子组件

<template>
  <div class="uploadDiv">
    <el-upload
      ref="upload"
      action="#"
      list-type="picture-card"
      :headers="headers"
      :limit="100"
       multiple
       drag
      :show-file-list="true"
      :auto-upload="false"
      :accept="picAccept"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :on-change="handleChange"
      :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <p v-show="fileList.length==0">支持图片拖入,一次最多上传100张,图片支持格式:jpg,png,bmp,gif,webp,tiff,svg,单张图片 < 10M</p>
</div>

</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  props: {
    fileList: {
       type: Array,
    },
    // 图片类型
    picAccept: {
      type: String,
      default:''
    },
  },
  data () {
    return {
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      dialogImageUrl: '',
      dialogVisible: false,
    }
  },
  methods: {
    handleChange (file, fileList) {
      //获取上传文件大小
      let imgSize = Number(file.size / 1024 / 1024);
        if (imgSize > 10) {
        this.$msgbox({
          title: "",
          message: "图片大小不能超过10MB,请重新上传。",
          type: "warning",
        });
        fileList.pop();   //新增的图片在最后一个,所以只要删除那个最后新增的>10M的图片就可以了
        return;
        }
      this.$emit('update:fileList', fileList)
     },
    handleRemove (file, fileList) {
      this.$emit('update:fileList', fileList)
    },
    handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
  }
}
</script>

<style lang="scss" scoped>
.uploadDiv{
  width: 100%;
  height: 100%;
  p{
    color: #737780;
  }
  ::v-deep .el-upload--picture-card{
    width: 228px;
    height: 208px;
  }
  ::v-deep .el-upload-list--picture-card .el-upload-list__item{
    width: 228px;
    height: 208px;

  }
  ::v-deep .el-upload--picture-card i{
    line-height: 7;
  }
    ::v-deep .el-upload-dragger{
    width: 226px;
    height: 206px;
  }
}
</style>

父组件使用方法

//导入子组件
import PicUpload from '../../../../components/PicUpload'

//data 中定义要传的参数
data(){
      fileList: [],
      picAccept: '.jpg,.png,.bmp,.gif,.webp,.tiff,.svg',
}

//methods中定义方法

    // 开始检测
    async startcheck () {
      // 上传图片到服务器
      if (this.fileList.length === 0) {
        this.$message.warning('请选取文件')
        return
      }
      const formData = new FormData()
      this.fileList.forEach(file => {
        formData.append('file', file.raw)
      })
      let res = await submitUploadApi(formData)
    },
    
     //清空
    clearUpload () {
      this.fileList = []
    },