使用来自 reactJS 的 POST 将带有令牌的图像上传到 fastAPI 路由

upload an image with a token to a fastAPI route using POST from reactJS

我正在尝试使用 post 方法

将图像从客户端 (reactJS) 上传到 fastAPI

这是我的客户端

const [img, setImg] = useState(null)

const onImageUpload = (e) => {
        console.log(e.target.files[0])
        setImg(e.target.files[0])
    }


const handleChange = () => {
        if (!img) setErr("please upload an image")
        else {
            
            let formData = new FormData();
            let token = localStorage.getItem("TikToken")

            formData.append(
                "token",
                token
            )
           
            formData.append(
                "pic",
                img,
                img.name
                )
                

            console.log(formData)
            axios({
                method: 'post',
                url: "http://localhost:8000/profile/pic/",
                data: formData
                
            })
            .then(function(response) {
                console.log(response);
            })

            
        }
    }

这是我的 fastAPI 函数

@app.post("/profile/pic/")
async def setpic(token: str, pic:bytes = File(...)):

    print(pic)
    image = Image.open(io.BytesIO(pic))
    image.show()
    # response = await store_profile_image(form, str(base64.b64encode(form)))
    return "response"
    

我收到错误 422(无法处理的实体)

这是错误

Edit:1 Uncaught (in promise) 
AxiosError {message: 'Request failed with status code 422', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code: "ERR_BAD_REQUEST"
config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
message: "Request failed with status code 422"
name: "AxiosError"
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response: {data: {…}, status: 422, statusText: 'Unprocessable Entity', headers: {…}, config: {…}, …}
[[Prototype]]: Error

我做错了什么? 以及如何修复它?

编辑:

我检查了错误正文(响应 > 数据 > 详细信息)

我找到了这个

detail: Array(1) 0: 
    loc: (2) ['query', 'token'] 
    msg: "field required" 
    type: "value_error.missing" 

我将 axios 请求中的数据更改为 data: { "token" : token, "pic": img}

我在错误正文中得到了这个

detail: Array(2)
0:
    loc: (2) ['query', 'token']
    msg: "field required"
    type: "value_error.missing"
    [[Prototype]]: Object
1:
    loc: (2) ['body', 'pic']
    msg: "field required"
    type: "value_error.missing"
    [[Prototype]]: Object
length: 2

要通过图像传递附加参数(即令牌),请使用 token:str = Form(...)

确实,为了传递图像,body 必须编码为 multipart/form-data 而不是 application/json。在这种情况下,路径参数必须是 FileForm.

类型

这不是 FastAPI 的限制,而是 HTTP 协议的一部分

@app.post("/profile/pic/")
async def setpic(token: str = Form(...), pic:bytes = File(...)):

    print(pic)
    image = Image.open(io.BytesIO(pic))
    image.show()
    # response = await store_profile_image(form, str(base64.b64encode(form)))
    return "response"

并将 header 添加到您的 axios 请求中

headers: {
   "Content-Type": "multipart/form-data",
 },