原生input文件上传+XMLHttpRequest请求

<div className={style.right_bottom_btn}>
    <label className={style.upLoad_btn}>
          <input ref={this.fileInput} type="file" onChange={this.onSelectChangeFile} accept='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel' multiple style={{display : 'none' }}/>
          {this.state.upLoadText}
    </label>
</div>
onSelectChangeFile= async (e)=>{
    const fileList = [...e.target.files]
    console.log('上传的文件---', fileList);
    console.log('window.userId:', window.userId, window.userName)
    if (fileList.some(item=> item.type !== 'application/vnd.ms-excel' && item.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
      Toast.info('请选择正确的文件类型!',2)
      return false
    }
    
    this.fileInput.current.value = null
    let requestArr = []
    for( let i = 0; i < fileList.length; i++) {
      let requestFile = this.httpUpLoadBatch(fileList[i])
      requestArr.push(requestFile)
    }
    Promise.all(requestArr).then(res=>{
      console.log('res===', res)
      Toast.success('上传成功!',2)
    }).catch(err=>{
      console.error('上传失败:', err) 
      Toast.info('上传失败,请刷新或稍后重试!',2)
    })
  }
  httpUpLoadBatch=(file)=>{
    return new Promise((resolve, reject) => {
      const formData = new window.FormData()
      formData.append('file', file)
      const xhr = new window.XMLHttpRequest()
      xhr.open('post', 'https://nczupload.carzone365.com/api/v1/public/upload/object/originName/batch')
      xhr.send(formData)
      xhr.onload = () => {
        if (xhr.status === 200) {
          const res  = JSON.parse(xhr.responseText)
          let url = ''
          if(res.code === 200) {
            url = res.data[0]
          } else {
            reject({code: res.code, msg: res.message})
          }
          resolve(url)
        } else {
          reject({code: xhr.status, msg: '系统异常'})
        }
      }
    })
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容