从 React 前端将图像上传到烧瓶后端时出现 KeyError 'image'
Posted
技术标签:
【中文标题】从 React 前端将图像上传到烧瓶后端时出现 KeyError \'image\'【英文标题】:KeyError 'image' when uploading image to flask backend from React frontend从 React 前端将图像上传到烧瓶后端时出现 KeyError 'image' 【发布时间】:2021-02-23 22:04:59 【问题描述】:我正在尝试将数据从我的反应前端上传到烧瓶后端,但是在上传后我收到以下错误:“400 错误请求:浏览器(或代理)发送了此服务器无法理解的请求。 KeyError: 'image'" 但是当我使用 Postman 表单数据上传图片时,它工作得很好。我的提取请求有问题吗?
import React from "react";
import useForm from "react-hook-form";
export default function App()
const register, handleSubmit = useForm();
const onSubmit = (data:any) => fetch("http://127.0.0.1:4000/upload",
method: 'POST',
mode: 'no-cors',
body: data,
).then(() => console.log(data))
return (
<form onSubmit=handleSubmit(onSubmit)>
<input ref=register type="file" name="image" required/>
<input type="submit" />
</form>
);
这是我的后端代码:
app = Flask(__name__, template_folder='.')
app.config['MAX_CONTENT_LENGTH'] = file_mb_max * 1024 * 1024
app.config['CORS_HEADERS'] = 'Content-Type'
CORS(app, support_credentials=True)
app.secret_key = app_key
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in extensions
def clear_folder(upload_dest):
for f in os.listdir(upload_dest):
os.remove(os.path.join(upload_dest, f))
@app.route('/upload', methods=['POST'])
def upload_file():
if request.method == 'POST':
print("DEBUG ----",request.files['image'])
file = request.files['image']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(upload_dest, filename))
file_path = os.path.join(upload_dest, filename)
type(file)
shot_type = detect_shot(file_path)
# clear_folder(upload_dest)
return jsonify('shotType': shot_type)
return redirect('/upload')
if __name__ == "__main__":
print('to upload files navigate to http://127.0.0.1:4000/upload')
app.run(host='127.0.0.1', port=4000, debug=True, threaded=True)
【问题讨论】:
【参考方案1】:修改获取请求以包含包含图像元素的formData,
const form = new FormData();
form.append('image', data);
fetch("http://127.0.0.1:4000/upload",
method: 'POST',
body: form,
)
不确定“模式”,但您可以尝试使用或不使用哪种解决方案。
【讨论】:
以上是关于从 React 前端将图像上传到烧瓶后端时出现 KeyError 'image'的主要内容,如果未能解决你的问题,请参考以下文章
尝试从客户端登录到后端烧瓶 api 时出现 401 UNAUTHORIZED 状态
在 React Native 中将图像上传到 Firebase 存储时出现错误 400 Bad Request
使用 AlamoFire 和预签名 URL 将图像上传到 S3 存储桶时出现问题