Using UploadFile for direct file upload without a multipart/form-data request

I have an FastAPI endpoint for handling file uploads that looks something like this:

@app.post('/upload')
async def accept_some_file(f: UploadFile):
    content = await f.read()
    # ... do stuff with content and generate a response

but this appears to only work with multipart/form-data encoded payloads.

I’d like to be able to send file bytes directly through a request that looks like this:

POST /upload HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.79.1
Accept: */*
Content-Type: image/jpeg
Content-Length: 11044

... image bytes

Is there a FastAPI setting I can use to allow this? Or is there another request type that makes more sense for this use case?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can get the request body as bytes using await request.body():

from fastapi import Request

@app.post('/upload')
async def accept_some_file(request: Request):
    body = await request.body()

or, you can also access the request body as a stream (in this way the byte chunks are provided without storing the entire body to memory) – see Starlette documentation. Example:

@app.post('/upload')
async def accept_some_file(request: Request):
    body = b''
    async for chunk in request.stream():
        body += chunk


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x