PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How to upload a file from React front end to FastAPI?

 October 14, 2022     axios, fastapi, file-upload, multipartform-data, reactjs     No comments   

Issue

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?


Solution

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.



Answered By - KingJac
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing