使用Reactjs和Flask上传文件

时间:2018-11-03 14:24:12

标签: python reactjs 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"

1 个答案:

答案 0 :(得分:2)

您可以改用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));
}