我尝试使用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"}
因为react和flask在不同的端口中运行,所以使用完整的URL。检查下面的代码
相关问题 更多 >
编程相关推荐