我正在尝试使用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"
答案 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));
}