原生JS 文件上传

一、目的:实现上传图片功能
二、效果
在这里插入图片描述
在这里插入图片描述

三、思路:用input标签自带的上传,先隐藏掉,给上传按钮添加点击事件,绑定input的点击事件
四、代码

//html
<input ref="img-upload-input" class="img-upload-input" type="file" accept=".png, .jpg" @change="submitUpload">
<el-button style="margin-top: 20px" type="primary" @click="handleSelectedImg">选择图片</el-button>
//js
//点击上传按钮
handleSelectedImg() {
 this.$refs['img-upload-input'].click()
},
 //选好图片之后点击打开按钮
submitUpload(e) {
  const files = e.target.files
  const rawFile = files[0] // only use files[0]
  if (!rawFile) return
  this.upload(rawFile)
},
 //上传
upload(rawFile) {
   this.$refs['img-upload-input'].value = null // fix can't select the same excel
   if (!this.beforeUpload) {
     return
   }
   //检查文件是否满足条件
   const before = this.beforeUpload(rawFile)
   if (before) {
   //上传事件
     this.uploadSectionFile(this.uploadParams, rawFile)
   }
},
beforeUpload(file) {
   const isLt1M = file.size / 1024 / 1024 < 50

   if (isLt1M) {
     return true
   }
   console.log('上传文件不超过50M', 'warning')
   return false
},
uploadSectionFile(params, file) {
   let data = params
   let fd = new FormData()// FormData 对象
   let fileObj = file// 相当于input里取得的files
   fd.append('stationID', data.stationID)
   fd.append('date', data.date)
   fd.append('file', fileObj)// 文件对象
   supplementFile(fd).then(res => {
     //调用上传接口
   })
}

五、注意事项
封装的请求头是(后面发现也不一定要配置这个)

'Content-Type': 'multipart/form-data;'

axios request的拦截转换直接return

transformRequest: [function(data) {
    // 对 data 进行任意转换处理
    return data
  }],

六、常见问题
1.上传文件的同时要传别的参数怎么办?
可以把参数和文件装在一个文件对象里面

let fd = new FormData()
fd.append('file', file)//文件
fd.append('param1', param)

2.文件大小的限制问题

  1. 前端上传文件时限制可选文件大小
  2. 后端Springboot限制
  3. nginx配置限制,当前端发送请求后端接收不到的时候,可以检查nginx配置。
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值