首页 > 编程技术 > js

原生JS实现文件上传

发布时间:2022-7-17 15:15 作者:Tiny2017

本文实例为大家分享了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配置。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

原文出处:https://blog.csdn.net/Tiny2017/article/details/115550913

标签:[!--infotagslink--]

您可能感兴趣的文章: