使用element-ui上传文件

使用element-ui上传文件

formData格式

组件

<el-upload
   style="width: 300px"
   class="upload-demo"
   drag
   multiple
   :on-success="upSuccess"
   :on-change="handleChange"
   :file-list="fileList"
   :http-request="httpRequest"
 >
 <i class="el-icon-upload" />
 <div class="el-upload__text">
      将文件拖到此处,或<em>点击上传</em>
 </div>
 <div slot="tip" class="el-upload__tip">
      只能上传jpg/png文件,且不超过500kb
  </div>
</el-upload>

方法

methods:{
 // 上传前判断文件格式及大小
    handleBeforeUpload(file, fileList) {
      let res = true
      // 判断文件格式
      const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png')
      const isPDF = file.type === 'application/pdf'
      if (!isJPG && !isPDF) {
        this.$message.error('上传文件只能是 图片 或 PDF 格式!')
        res = false
      }

      // 判断文件大小
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
        res = false
      }

      // 判断文件是否已经上传过
      for (const i in fileList) {
        if (fileList[i].name === file.name) {
          this.$message.error('该文件已上传过,请选择其他文件')
          res = false
        }
      }

      return res
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      for (const i in fileList) {
        if (fileList[i].name === file.name) {
          fileList.splice(i, 1)
          return
        }
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning('最多上传一个文件,请先删除再重新上传')
    }
  },
 // 文件上传
    uploadManSystemScanFile(file) {
      console.log(file) // 上传的文件
      Uploadimg(file).then(res => {
        if (res.code === 200) {
          this.$message.success('文件上传成功')
        }
      })
    },
}

请求函数(api)

// 图片上传
export function Uploadimg(fileobj) {
  const param = new FormData()
  param.append('file', fileobj.file)
  return request({
    url: 'file/uploadFile',
    method: 'post',
    headers: { 'Content-Type': 'multipart/form-data' },
    data: param
  })
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值