fastapi: Fileupload failed.

Description

I’ve tried a sample code for upload my file but it failed.

from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/files/")
async def create_file(file: bytes = File(...)):
    return {"file_size": len(file)}


@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

Result error

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 16 (5 by maintainers)

Most upvoted comments

@amanjazari

It’s worth checking if you have python-multipart installed in your environment.

Via pip install python-multipart you will install the package and this may well solve your issue.

EDIT: This tip is also present in the official docs now: https://fastapi.tiangolo.com/tutorial/request-files/

The latest versions (for quite a while now) detect if you use something that would require python-multipart and error out quickly giving you instructions about how to fix it.

Also, @whillas, that’s not the way to ask. I’m giving you this for free, working on it in my free time. And everyone here is helping in their free time mostly. Please try to be more respectful.

Christ, i spent half a day on this. why don’t you have python-multipart as a requirement of this module?!?!?

Thanks for the help and discussion here everyone!

Was your issue solved @amanasmuei ?

@davidefiocco My problem was identical and installing python-multipart solved it. Thanks!

@dmontagu ,

Below is the script i used to test file upload as per tutorial at https://fastapi.tiangolo.com/tutorial/request-files/

from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/files/")
async def create_file(file: bytes = File(...)):
    return {"file_size": len(file)}


@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

Curl command at swagger curl -X POST "http://url/uploadfile/" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "file=@cfm.txt;type=text/plain"