我正在尝试使用React上传文件,并使用post请求将其传递到flask后端。但是我得到的错误是Failed to load resource: the server responded with a status of 400 (BAD REQUEST)
。
我不知道问题所在。如果还有其他可能的方法,那也会有所帮助。
这是upload.js:
import axios from 'axios';
import React from 'react';
class UploadVideo extends React.Component {
constructor(props) {
super(props);
this.state = {
imageURL: '',
};
this.handleUploadImage = this.handleUploadImage.bind(this);
}
handleUploadImage(ev) {
ev.preventDefault();
const data = new FormData();
data.append('file', this.uploadInput.files[0]);
data.append('filename', this.fileName.value);
console.log(data)
axios('/upload', {
method: 'POST',
body: data,
}).then((response) => {
console.log(response)
}).catch(err => {
console.log(err)
});
}
render() {
return (
<form onSubmit={this.handleUploadImage}>
<div>
<input ref={(ref) => { this.uploadInput = ref; }} type="file" />
</div>
<div>
<input ref={(ref) => { this.fileName = ref; }} type="text" placeholder="Enter the desired name of file" />
</div>
<br />
<div>
<button type="submit" className="btn">Upload</button>
</div>
<img src={this.state.imageURL} alt="img" />
</form>
);
}
这是烧瓶中的index.py:
@app.route('/upload', methods=['POST'])
def fileUpload():
file = request.files['file']
filename = secure_filename(file.filename)
print(request.body, '1')
return {"message":"Saved"}
答案 0 :(得分:0)
因为反应和运行在不同端口中的烧瓶使用完整URL。检查下面的代码
handleUploadImage(ev) {
ev.preventDefault();
const data = new FormData();
data.append('file', this.uploadInput.files[0]);
data.append('filename', this.fileName.value);
console.log(data)
axios('http://localhost:8000/upload', {
method: 'POST',
body: data,
}).then((response) => {
console.log(response)
}).catch(err => {
console.log(err)
});
}