首页 > 解决方案 > 在一个 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'

我究竟做错了什么 ?

标签: reactjsflaskaxios

解决方案


您创建了一个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 => { ...

推荐阅读