如何将文件从React前端上传到FastApi?

发布于 2025-02-08 18:25:25 字数 1179 浏览 2 评论 0原文

正如标题所说,我正在尝试将文件从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:

enter image description here

I am not quite familiar with the rules and format needed behind file uploading. Could someone clear my confusion?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

聊慰 2025-02-15 18:25:38

op 更新:
如果有人想添加有关为什么有效的更多信息,请替换Axios零件来解决问题

const headers={'Content-Type': file[0].type}
await axios.post("/uploadfile",formdata,headers)
    .then()//etc

,请随时这样做 - 因为我也不确定。

Update from OP:
I have managed to solve the problem by replacing the axios part with

const headers={'Content-Type': file[0].type}
await axios.post("/uploadfile",formdata,headers)
    .then()//etc

if anyone want to add more information on why that works please feel free to do so - since I'm not quite sure either.

夏雨凉 2025-02-15 18:25:27

这对我在代码中找到错误很有帮助。我怀疑您的问题是在第一次尝试中将formdata嵌套在另一个对象中:axios.post(“/uploadfile”,{file:file:formdata} ...应该是< code> axios.post(“/uploadfile”,formdata ... 。

对我来说,诀窍是确保formdata.append.append

> uploadfile

formdata.append("file123", file[0])
axios.post("/uploadfile", formdata ...etc...

async def create_upload_file(file123: UploadFile = File(...)): ...etc...

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 be axios.post("/uploadfile", formdata ....

For me, the trick was ensuring that the key to the formData.append exactly matches the name of the UploadFile parameter for my FastAPI endpoint.

In this example the name is file123.

In the React code you have:

formdata.append("file123", file[0])
axios.post("/uploadfile", formdata ...etc...

And in the Python code you have:

async def create_upload_file(file123: UploadFile = File(...)): ...etc...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文