如何将文件从React前端上传到FastApi?
正如标题所说,我正在尝试将文件从React前端上传到FastApi。我使用的代码如下:
//this is backend FastAPI ==================
@app.post("/uploadfile")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
//frontend ===================================
const [file, uploadFile] = useState(null)
//when upload button clicked
function handleSubmit(){
console.log(file[0].name)
const formdata = new FormData();
formdata.append(
"file",
file[0],
)
axios.post("/uploadfile", {
file:formdata}, {
"Content-Type": "multipart/form-data",
})
.then(function (response) {
console.log(response); //"dear user, please check etc..."
});
}
// this is when file has been selected
function handleChange(e){
uploadFile(e.target.files); //store uploaded file in "file" variable with useState
}
它返回一个422(无法处理的实体)。 Axios的消息详细信息是:
我对文件上传后需要的规则和格式并不熟悉。有人可以清除我的困惑吗?
as the title says, I'm trying to upload a file from React front end to FastAPI. The code I used is below:
//this is backend FastAPI ==================
@app.post("/uploadfile")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
//frontend ===================================
const [file, uploadFile] = useState(null)
//when upload button clicked
function handleSubmit(){
console.log(file[0].name)
const formdata = new FormData();
formdata.append(
"file",
file[0],
)
axios.post("/uploadfile", {
file:formdata}, {
"Content-Type": "multipart/form-data",
})
.then(function (response) {
console.log(response); //"dear user, please check etc..."
});
}
// this is when file has been selected
function handleChange(e){
uploadFile(e.target.files); //store uploaded file in "file" variable with useState
}
It returns a 422 (Unprocessable Entity). The message detail from axios is:
I am not quite familiar with the rules and format needed behind file uploading. Could someone clear my confusion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
op 更新:
如果有人想添加有关为什么有效的更多信息,请替换Axios零件来解决问题
,请随时这样做 - 因为我也不确定。
Update from OP:
I have managed to solve the problem by replacing the axios part with
if anyone want to add more information on why that works please feel free to do so - since I'm not quite sure either.
这对我在代码中找到错误很有帮助。我怀疑您的问题是在第一次尝试中将
formdata
嵌套在另一个对象中:axios.post(“/uploadfile”,{file:file:formdata} ...
应该是< code> axios.post(“/uploadfile”,formdata ... 。对我来说,诀窍是确保
formdata.append.append
与。
> uploadfile
我
This was helpful for me finding a bug in my code. I suspect your problem was nesting the
formData
inside another object in your first attempt:axios.post("/uploadfile", {file:formdata} ...
should beaxios.post("/uploadfile", formdata ...
.For me, the trick was ensuring that the key to the
formData.append
exactly matches the name of theUploadFile
parameter for my FastAPI endpoint.In this example the name is
file123
.In the React code you have:
And in the Python code you have: