python 使用React将图像发送到Flask服务器

eyh26e7m  于 2023-06-04  发布在  Python
关注(0)|答案(1)|浏览(238)

我想将图像传输到服务器,保存指向此图像的链接,然后将此图像上载到我的产品。但是当我点击保存按钮将数据发送到服务器时,我得到一个错误415(不支持的媒体类型)。我该怎么解决这个问题?
我的React文件Product.jsx

const handleChange = (e) => {
    if (e.target.name === "image") {
      setFormData({
        ...formData,
        [e.target.name]: e.target.files[0],
      });
    } else {
      setFormData({
        ...formData,
        [e.target.name]: e.target.value,
      });
    }
  };

  useEffect(() => {
    console.log(formData.food_drink);
  }, [formData.food_drink]);

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);

    const postData = new FormData();
    postData.append("name", formData.name);
    postData.append("ingredients", formData.ingredients);
    postData.append("price", formData.price);
    postData.append("food_drink", formData.food_drink);
    postData.append("image", formData.image);

    fetch("/addProduct", {
      method: "POST",
      headers: { "content-type": "multipart/form-data" },
      body: postData,
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        setFormData({
          ...formData,
          food_drink: "pizza",
          ingredients: "",
          name: "",
          price: "",
          image: null,
        });
      })
      .catch((error) => {
        console.error(error);
      });
  };

我的Flask文件srver.py

import os
import sqlite3
from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename

app = Flask(__name__)

UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/addProduct', methods=['POST'])
def add_product():
    name = request.json["name"]
    ingredients = request.json["ingredients"]
    price = request.json["price"]
    food_drink = request.json["food_drink"]
    file_img = request.files["image"]
    print(file_img)
    if file_img:
        filename = secure_filename(file_img.filename)
        file_img.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    db = sqlite3.connect('flask-server\db\main_db.db')
    sql = db.cursor()
    sql.execute("INSERT INTO products (name, ingredients, price, food_drink, image) VALUES (?, ?, ?, ?, ?)", (name, ingredients, price, food_drink, (os.path.join(UPLOAD_FOLDER, filename))))
    db.commit()
    db.close()
    return jsonify({"message": "200"})

if __name__ == "__main__":
    app.run(debug=True)

从服务器上载我在项目根目录中创建的文件夹

dsf9zpds

dsf9zpds1#

您遇到的错误415(UNSUPPORTED MEDIA TYPE),发生的原因是Flask服务器期望请求的内容类型是“multipart/form-data”,因为您正在发送图像文件。然而,在你的React代码中,你错误地将“content-type”头设置为“multipart/form-data”。
要解决此问题,您需要从fetch请求中删除“content-type”标头,并让浏览器在发送FormData时自动设置它。以下是React文件中fetch请求的修改代码:

fetch("/addProduct", {
  method: "POST",
  body: postData,
})
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
    setFormData({
      ...formData,
      food_drink: "pizza",
      ingredients: "",
      name: "",
      price: "",
      image: null,
    });
  })
  .catch((error) => {
    console.error(error);
  });

通过删除“headers”属性,浏览器将自动为FormData设置适当的内容类型标题,包括多部分表单数据所需的边界。
此外,确保“uploads”文件夹存在于Flask服务器的根目录中,并且它具有保存上传文件所需的写入权限。

相关问题