element上传文件二次封装

子组件

<template>
  <div :class="{ 'hide': fileLength >= limit }">
    <!-- 图片上传 -->
    <el-upload ref="uploadImg" class="uploadImg" :class="{ uploadImgSmall: size == 'small' }" :action="actionUrl"
      name="upload" :disabled="componentDisabled" :list-type="listType" :show-file-list="showFileList" :limit="limit"
      :multiple="multiple" :file-list="bindFileList" :before-upload="beforeAvatarUpload" :on-change="handlePictureChange"
      :on-preview="handlePictureCardPreview" :on-success="handlePictureSuccess" :on-error="handlePictureError"
      :on-remove="handleRemove" :on-exceed="handleExceed">
      <el-button size="small" type="primary" style="height:29px;padding:0 15px;line-height:29px;">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
import * as imageConversion from 'image-conversion'

export default {
  props: {
    value: {
      type: [Array, String],
      default: []
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 最多选择多少张
    limit: {
      type: Number,
      default: 20
    },
    // 上传路径
    action: {
      type: String,
      default: ''
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否显示已上传文件列表
    showFileList: {
      type: Boolean,
      default: true
    },
    // 文件列表的类型 text/picture/picture-card
    listType: {
      type: String,
      default: 'text'
    },
    // 图片路径前缀
    target: {
      type: String,
      default: ''
    },
    // 显示样式
    viewType: {
      type: String,
      default: 'picture'
    },
    // 组件大小控制 默认不传
    // 可选值 [small]
    size: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 绑定值类型
      valueTypeof: this.value ? typeof this.value : 'string',
      // 上传api路径
      actionUrl: this.action,
      // 上传文件显示
      bindFileList: [],
      // 上传文件记录
      propsList: [],
      // 组件loading
      componentLoading: false,
      // 当前的文件长度
      fileLength: 0,
      // 上传图片状态记录
      uploadState: {
        checkedFileLength: 0, // 选择的图片数量
        fulfilFileLength: 0 // 上传完成的图片数量
      },
      // Element notify通知 Promise 对象
      notifyPromise: Promise.resolve()
    }
  },
  computed: {
    componentDisabled() {
      return this.componentLoading || this.disabled
    }
  },
  created() {
    console.log('上传数据', this.value)
    // 数据处理
    let tempValue = this.value
    if (this.valueTypeof === 'string') {
      tempValue = tempValue ? tempValue.split(',') : []
    }
    this.fileLength = tempValue.length
    tempValue.forEach((item, index) => {
      this.bindFileList.push({
        name: item,
        url: this.target + item,
        response: {
          code: 1,
          data: item
        }
      })
    })
  },
  methods: {

    // 重置数据
    reset_data() {
      this.$refs['uploadImg'].clearFiles()
      this.fileLength = 0
    },

    // 图片上传限制
    beforeAvatarUpload(file) {
      const fileSize = file.size / 1024 // 单位KB
      if (fileSize < 2) {
        this.notifyPromise = this.notifyPromise.then(() => {
          this.$notify.error({ title: '错误提示', message: file.name + '不能小于 2KB!' })
        })
        return false
      }
      this.componentLoading = true
      this.uploadState.checkedFileLength++
      if (fileSize / 1024 > 2) {
        return new Promise((resolve, reject) => {
          imageConversion.compressAccurately(file, 500).then(res => {
            resolve(res)
          })
        })
      }
      return true
    },
    // 文件状态改变时
    handlePictureChange(file, fileList) {
      this.fileLength = fileList.length
    },
    // 图片上传成功
    handlePictureSuccess(response, file, fileList) {
      this.uploadState.fulfilFileLength++
      // file.name = file.response.data
      if (this.uploadState.fulfilFileLength === this.uploadState.checkedFileLength) {
        this.emitInputFun(fileList)
      }
    },
    // 图片上传失败
    handlePictureError(err, file, fileList) {
      this.uploadState.fulfilFileLength++
      this.notifyPromise = this.notifyPromise.then(() => {
        this.$notify.error({ title: '错误提示', message: file.name + '上传失败' })
      })
      if (this.uploadState.fulfilFileLength === this.uploadState.checkedFileLength) {
        this.emitInputFun(fileList)
      }
    },
    // 图片删除
    handleRemove(file, fileList) {
      this.fileLength = fileList.length
      if (this.uploadState.fulfilFileLength === this.uploadState.checkedFileLength) {
        this.emitInputFun(fileList)
      }
    },
    // list图片预览
    handlePictureCardPreview(file) {
      window.open(file.url)
    },
    // 图片超出数量限制
    handleExceed() {
      this.$message.error('文件超过限制')
    },
    // 响应数据
    emitInputFun(fileList) {
      let tempValue = []
      fileList.forEach(item => {
        if (item.response && item.response.code === 0) {
          tempValue.push(item.response.result)
        }
      })

      if (this.valueTypeof == 'string') {
        tempValue = tempValue.join(',')
      }
      console.log(fileList[0].name)
      this.$emit('filename', fileList[0].name)
      this.$emit('input', tempValue)
      // 通知父级执行form验证
      this.$emit('callBack')

      this.componentLoading = false
    }
  }
}
</script>

<style scoped>
.hide>>>.el-upload {
  display: none;
}

.el-button+.el-button {
  margin-left: 0;
}

/*small组件*/
.uploadImgSmall>>>.el-upload-list--picture-card .el-upload-list__item {
  width: 80px;
  height: 80px;
}

.uploadImgSmall>>>.el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 88px;
}
</style>

父组件

<template>
  <el-dialog :title="!dataForm.cateId ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="dataForm.name" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="手机号"></el-input>
      </el-form-item>
      <!-- <el-form-item label="身份证号" prop="cateName">
        <el-input v-model="dataForm.cateName" placeholder="身份证号"></el-input>
      </el-form-item> -->
      <el-form-item label="上传文件" prop="reportUrl">
        <!-- <el-upload class="upload-demo" action="http://admin.qiuxiangjk.com:8087/admin/common/upload" :on-preview="handlePreview"
          :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="3" :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
        </el-upload> -->
        <!-- <uploadFile v-model="dataForm.cateName"></uploadFile> -->

        <!--   -->
        <uploadFile v-model="dataForm.reportUrl" action="http://admin.qiuxiangjk.com:8087/admin/common/upload" :limit="1"
        ref="reset" @callBack="$refs.dataForm.validateField('reportUrl')" />
      </el-form-item>


    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import uploadFile from "@/components/Upload/uploadFile";
export default {
  components: { uploadFile },

  data() {
    return {
      list:1,
      url: "",
      visible: false,
      dataForm: {
        name: "",
        phone: "",
        reportUrl: "",
      },
      uploadVisible: false,
      dataRule: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
        ],
        reportUrl: [
          { required: true, message: "报告文件不能为空", trigger: "blur" },
        ],
      },

      // 上传文件列表
      fileList: []
    };
  },
  created() {
 console.log('上传数据')
  },
  methods: {
    // 上传文件
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`);
    },
    // 结束
    init(id) {
      this.dataForm.id = id || 0;
      this.url = this.$http.adornUrl(
        `/sys/oss/upload?token=${this.$cookie.get("token")}`
      );
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/admin/hpv/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm = data.hpv
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/admin/hpv/${!this.dataForm.cateId ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData(this.dataForm),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
              // 重置表单
              this.$refs.reset.reset_data()
              this.dataForm.reportUrl=""
              this.$refs["dataForm"].resetFields();
              this.$router.push("/admin-report");

            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    handleIconSuccess(response) {
      this.dataForm.coverImage = response.url;
      this.$forceUpdate();
    },







  },
};
</script>
<style lang="scss">
.formInfo {
  line-height: 0px;
  color: #999999;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值