我试图使用axios从我的react-admin
应用程序上传一个图像到FastAPI。ImageInput
组件返回一个File
对象,我将该对象转换为Blob
并尝试使用axios
上传。
我使用的API客户机是由奥瓦尔生成的。
发送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:
# ...
在浏览器中开发工具的“网络”部分,它将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
请求应该是什么样的呢?
发布于 2022-01-23 16:41:24
如下所示(请记住根据您的url
端点更改Accept
头以及FastAPI头):
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/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(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
}
}
</script>
<input type="file" id="fileInput" name="file"><br>
<input type="button" value="submit" onclick="uploadFile()">
https://stackoverflow.com/questions/70824033
复制相似问题