繁体   English   中英

用Reactjs和Flask上传文件

[英]file upload with Reactjs and Flask

我正在尝试使用reactjs从前端上传文件。 后端是Flask python。 我收到响应代码400。我在做什么错?

前端 :

<input type="file" name="file" onChange={this.onChangeFile}/>
<button onClick={this.uploadFile}>
    Upload 
</Button>

uploadFile(e){
    e.preventDefault()
    let f = this.state.fileToBeSent
    let f_name = this.state.fileToBeSent.name
    console.log(f_name)

    let fileReader = new  FileReader()
    fileReader.readAsDataURL(f)
    fileReader.onload = (e) => {

      let toPost = {
        'file_name' : f_name,
        'file_data': e.target.result
      }
      console.log(toPost)
      return axios.post('/api/upload', toPost)
                  .then(res => console.log(res))
                  .catch(err => console.warn(err))
    }

  }

在后端:

@app.route('/api/upload', methods = ['POST'])
def upload_file():
    file = request.files['file']
    print(file)
    return "done"

您可以使用FormData来发送文件。

uploadFile(e) {
  e.preventDefault();
  let file = this.state.fileToBeSent;
  const formData = new FormData();

  formData.append("file", file);

  axios
    .post("/api/upload", formData)
    .then(res => console.log(res))
    .catch(err => console.warn(err));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM