从AXios上载单个图像到FastAPI:"预期UploadFile,收到:<class'str'>" [英] Upload single image from axios to FastAPI: "Expected UploadFile, received: <class 'str'>"

查看:0
本文介绍了从AXios上载单个图像到FastAPI:"预期UploadFile,收到:<class'str'>"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用axios将图像从我的react-admin应用程序上传到FastAPI。组件返回File对象,我将其转换为Blob并尝试使用axios上载。
我正在使用的API客户端已由orval生成。

我发送POST

后收到的响应
{
    "detail":[
        {
            "loc":[
                "body",
                "file"
            ],
            "msg":"Expected UploadFile, received: <class 'str'>",
            "type":"value_error"
        }
    ]
}

axios请求函数:

/**
 * @summary Create Image
 */
export const createImage = (
  bodyCreateImageImagesPost: BodyCreateImageImagesPost,
  options?: AxiosRequestConfig
): Promise<AxiosResponse<Image>> => {
  const formData = new FormData();
  formData.append(
    "classified_id",
    bodyCreateImageImagesPost.classified_id.toString()
  );
  formData.append("file", bodyCreateImageImagesPost.file);

  return axios.post(`/images`, formData, options);
};

axios请求头:

POST /images HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0
Accept: application/json, text/plain, */*
Accept-Language: pl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Authorization: bearer xxx
Content-Type: multipart/form-data; boundary=---------------------------41197619542060894471320873154
Content-Length: 305
Origin: http://localhost:3000
DNT: 1
Connection: keep-alive
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Sec-GPC: 1

请求数据对象:

{
  "classified_id": 2,
  "file": {
    "rawFile": {...},
    "src": "blob:http://localhost:3000/9826efb4-875d-42f9-9554-49a6b13204be",
    "name": "Screenshot_2019-10-16-18-04-03.png"
  }
}

FastAPI终结点:

def create_image(
    classified_id: int = Form(...),
    file: UploadFile = File(...),
    db: Session = Depends(get_db),
    user: User = Security(manager, scopes=["images_create"]),
) -> Any:
    # ...

在浏览器的开发人员工具的&Network";部分中,它将file字段显示为[object Object],但我猜这只是Blob没有字符串表示的问题?

当我尝试通过Swagger用户界面上传图像时,它按预期工作,curl请求如下所示:

curl -X 'POST' 
  'http://localhost:8000/images' 
  -H 'accept: application/json' 
  -H 'content-length: 3099363' 
  -H 'Authorization: Bearer xxx' 
  -H 'Content-Type: multipart/form-data' 
  -F 'classified_id=2' 
  -F 'file=@Screenshot_2019-10-16-18-04-03.png;type=image/png'

您知道这里出了什么问题吗?正确的axios请求应该是什么样子?

URL

使用方法如下(将推荐答案终结点的名称以及接受标头更改为您正在使用的名称):

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script type="text/javascript">
function uploadFile() {
    var formData = new FormData();
    var fileInput = document.getElementById('fileInput');
    if (fileInput.files[0]) {
        formData.append("classified_id", 2);
        formData.append("file", fileInput.files[0]);
        axios({
                method: 'post',
                url: '/upload',
                data: formData,
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'multipart/form-data'
                },
            })
            .then(function(response) {
                console.log(response);
            })
            .catch(function(response) {
                console.log(response);
            });
    }
}
</script>
 <input type="file" id="fileInput" name="file"><br>
 <input type="button" value="submit" onclick="uploadFile()">

这篇关于从AXios上载单个图像到FastAPI:&quot;预期UploadFile,收到:&lt;class&#39;str&#39;&gt;&quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆