vue-原生js实现文件上传

15 篇文章 0 订阅

1.按钮通过ref触发input的上传功能

<tk-button @click="handleUpLoad">点击上传</tk-button>(自定义标签)
<input ref="inputUpLoad" style="display: none" type="file" accept="*" @change="handleFile"/>

 handleUpLoad指向input

handleUpLoad () {
      if (this.radioDate.length === 0) {
        this.$alert('请先选择数据')
        return false
      }
      this.$refs.inputUpLoad.click()
    }

handleFile定义上传过程

handleFile (e) {
      let $target = e.target || e.srcElement
      let file = $target.files[0]
      if (!file) {
        return
      }
      let formData = new FormData()
      formData.append('file', file)
      // 图片上传限制
      let fileSize = file.size
      if (fileSize > 52428800) {
        this.$alert('大小不得超过50M')
        return
      }
      this.$axios({
        url: '/upload/file',
        method: 'post',
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        },
        data: formData
      }).then((res) => {
        // console.log(res.data)
        if (res.data.tradeMap.resultCode === '0000') {
          this.fileNames = res.data.tradeMap.fileNames
          // console.log('文件上传返回的filenames是:' + this.fileNames)
          this.sendFileNames()
        } else {
          let message = res.data.tradeMap.message
          this.$alert(message)
        }
      }).catch((error) => {
        console.log(error)
      })
    }

2.实现效果

 

一些校验及上传都能实现

3.缺陷

 1)从第二次上传开始,上传框中会遗留上次上传的文件名

2)上传失败后,需要点开上传框,点击取消,才能再次使用上传功能

 

 

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值