我正在try 使用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请求中的数据更改为

我在错误的身体里找到了这个

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(...)

事实上,为了传递图像,身体必须编码为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"

并将标题添加到axios请求中

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

Reactjs相关问答推荐

单击按钮时在子元素中不显示任何内容-react

可选链和useState挂钩

Reactjs中的chartjs和reaction-chartjs-2的问题

捕获表单数据时的Reactjs问题

如何使ionic 面包屑在州政府条件下可点击?

Antd V5组件自定义主题

尽管所有页面在 Reactjs 中都是公开的,但始终导航到特定页面

如何更新 FunctionComponentElement 的 props

如何在next.js 13中仅在主页导航栏上隐藏组件?

使用新数据更新时,React 不更新具有过滤功能的深层嵌套对象数组中的变量状态

useEffect 渲染没有依赖数组的组件

如何在react 中正确销毁上下文?

无法在 reactJS 中使用空包装器 <>

Cypress - 替换 React 项目中的变量

Mui CardMedia 的图片组件

如何在react 日历中自定义带有圆形边框的日期项?

网格项不缩小以适应包含的可滚动列表

在react 路由dom版本6中的组件内添加路由

React.js 中的页面崩溃(读取未定义的属性)

React-Native PDF 注释