美文网首页
07-手动上传文件-(Content-Type)

07-手动上传文件-(Content-Type)

作者: 零涂 | 来源:发表于2022-09-06 11:12 被阅读0次
//react代码
render(){
  <Button
    size="small"
    style={{
      marginLeft: 8,
      backgroundColor: 'rgb(216,45,0)',
      color: '#fff',
      border: 'rgb(216,45,0)',
    }}
    onClick={()=>this.importInputEl.click()}
  >
  导入
  </Button>
  <input 
    type="file" 
    ref={(ref)=>(this.importInputEl=ref)} 
    style={{display:'none'}} 
    onChange={this.fileImport}
  ></input>
}
//导入
fileImport=(info)=>{
  console.log('info',info);
  if(!this.importInputEl.files.length){
    message.warning('请选择文件')
    return ;
  }
  console.log('值',this.importInputEl.files[0])
  const formData = new FormData();
  formData.append('file',this.importInputEl.files[0]);
  let params = {
    token: sessionStorage.getItem('token'),
    file:formData
  }
  console.log('params',params);
  //此处调上传接口,formData应直接传入body。
}

需要注意的是,headers中的Content-Type最好不传。
POST请求时发送FormData类型的数据会将Content-Type设置multipart/form-data,完整的设置如下:

Content-Type: multipart/form-data; boundary=xxxx

但很可惜的是,我们在上传文件时并不知道formData对象里面的boundary分隔符是什么,冒然添加的话会出错的。

https://zhuanlan.zhihu.com/p/195726295
网上找到的这篇文章感觉解释的非常完整,可以收藏参考。

相关文章

网友评论

      本文标题:07-手动上传文件-(Content-Type)

      本文链接:https://www.haomeiwen.com/subject/cghgnrtx.html