无法加载资源:服务器在 reactjs 中以 python api 状态响应 422(无法处理的实体)

Failed to load resource: the server responded with a status of 422 (unprocessable entity) in reactjs with python api

我正在使用 python api 和 openCV 开发 reactjs,在上传照片 returns 后,面部周围会出现绿色矩形。所以处理它,点击上传照片 returns 422(不可处理的实体)。我有三个主要部分 Upload.js 用于前端上传部分,main.py 图片 api 和 face_detector.py 用于 opencv 部分。

Upload.js

import React, { useState } from 'react'
import './Upload.css'
import axios from 'axios';

const Upload = () => {
    const [file, setFile] = useState();



    const handleChange = (event) => {
        setFile(URL.createObjectURL(event.target.files[0]))
    }
    const submitForm = () => {
        const formData = new FormData();
        formData.append('file', file);


        axios
            .post('http://127.0.0.1:8000/images', formData, {
                headers: {
                    accept: 'multipart/form-data',
                }
            })
           
              .then(() => {
                alert('file upload succcess');
            })
            .catch(() => alert("File Upload Error"))
        return formData


    }


    return (
        <>
            <input className='img_choose' type="file" onChange={handleChange} />
            <img src={file} className='prev_img' alt='img' />
            <button className='btn_upload' onClick={submitForm}>Upload</button>
        </>
    );
}


export default Upload 

main.py

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import Response
from random import randint
from starlette.requests import Request
import uuid
from fastapi.middleware.cors import CORSMiddleware


app = FastAPI()

db = []

origins = [
    "http://localhost:3000",
    "http://127.0.0.1:8000/"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/main")
def main():
    return{"message":"Welcome"}


@app.post("/images/")
async def create_upload_file(file: UploadFile = File(...)):

    file.filename = f"{uuid.uuid4()}.jpg"
    contents = await file.read()  # <-- Important!

    db.append(contents)

    return {"filename": file.filename}


@app.get("/images/")
async def read_random_file():
# get a random file from the image db
 random_index = randint(0, len(db) - 1)
 response = Response(content=db[random_index])
 return response

Face_detector.py

import cv2
import urllib.request
import numpy as np


url = [
    "http://127.0.0.1:8000/images/"
]


def url_to_image(url):
    # download the image, convert it to a NumPy array, and then read
    # it into OpenCV format
    resp = urllib.request.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)

    # return the image
    return image


for url in url:
    trained_face_data = cv2.CascadeClassifier(
        'haarcascade_frontalface_default.xml')
    x = y = w = h = int
    image = url_to_image(url)
    face_coordinates = trained_face_data.detectMultiScale(image,
                                                          scaleFactor=1.1,
                                                          minNeighbors=5,
                                                          minSize=(30, 30),
                                                          flags=cv2.CASCADE_SCALE_IMAGE)
    for (x, y, w, h) in face_coordinates:
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)

这就是你做错的地方。

setFile(URL.createObjectURL(event.target.files[0]))

您在 formData 中附加文件 URL 而不是文件。

改用这个

setFile(event.target.files[0])