使用Axios向FastAPI上传文件时遭遇422 (Unprocessable Entity)错误求助
解决Axios上传文件到FastAPI出现422错误的问题
问题排查与修复点:
- 变量引用错误:React提交函数的参数是
acceptedFiles,但代码里用了未定义的file变量,需从acceptedFiles中获取实际文件。 - 错误的Accept请求头:设置的
Accept: "application/solidarity"不符合FastAPI默认的响应格式,应改为application/json或直接移除该头。 - 手动设置Content-Type导致解析失败:上传
FormData时,Axios会自动生成包含正确boundary的Content-Type头,手动设置"multipart/form-data"会丢失boundary,导致FastAPI无法解析表单数据,需移除该手动设置。
修改后的React提交函数:
const handleSubmit = async (acceptedFiles) => { // 单文件上传时取第一个文件,多文件需循环处理 const file = acceptedFiles[0]; if (!file) return; const formData = new FormData(); formData.append("file", file); try { const response = await axios.post( "http://127.0.0.1:8000/upload", formData, { headers: { Accept: "application/json", // 移除手动设置的Content-Type,交由Axios自动处理 }, } ); if (response.status >= 200 && response.status < 300) { console.log(response.data); // 处理审计结果逻辑 } else { throw new Error("Server responded with a non-2xx status code"); } } catch (error) { console.error( "Error uploading file:", error.response?.data || error.message ); } };
额外检查项:
- 确认FastAPI中的
UPLOAD_DIR已创建,且服务进程对该目录有写入权限。 - 若需支持多文件上传,需修改FastAPI接口为
async def upload_file(files: List[UploadFile]),同时React侧循环将文件添加到FormData中。
内容的提问来源于stack exchange,提问作者Parasite -
相关产品推荐
相关产品推荐

