reactjs - 在一个 post 请求中发送图像文件和数据
问题描述
我正在尝试通过以下方式在一个帖子请求中发送图像文件和数据axios
:
const fd = new FormData();
fd.append("image", selectedFile, selectedFile.name);
let data = {
category: category,
title: title,
post: text,
image: fd
};
//console.log(fd);
const headers = {
"Content-Type": "multipart/form-data"
};
const url = "http://localhost:5000/blog/posts";
axios
.post(url, fd, headers)
.then(resp => { ...
烧瓶后端:
image = request.files['image']
category = request.files['category']
title = request.files['title']
post = request.files['post']
日志输出:
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'category'
我究竟做错了什么 ?
解决方案
您创建了一个data
对象,但似乎没有对它做任何事情。如果您正在使用FormData
,则应将所有数据点附加到它。所以你的代码应该是这样的:
const fd = new FormData();
fd.append("image", selectedFile, selectedFile.name);
fd.append("category", category);
fd.append("title", title);
...
然后你可以按照你发布的方式发布它:
axios
.post(url, fd, headers)
.then(resp => { ...
推荐阅读
- javascript - 升序或降序排序在 Safari 桌面上不起作用
- reactjs - 在 Heroku Deploy 上找不到但在本地找到的模块
- c - C程序采用字母电话号码并转换为数字形式
- javascript - 如何在Javascript中将字符串的元素从左到右替换为从右到左?
- java - 是什么导致 Java 版本随机游走不收敛到预期值?
- macos - 安装 PyGObject 时出错,找不到“glib-object.h”文件
- rails-activestorage - ActiveStorage::PurgeJob 可以排入“默认”以外的队列吗?
- git - 使用 git 下载,没有 repo 数据和本地文件夹
- mysql - MySQL 过程子查询返回 null
- r - purrr:map中字符向量的占位符?