Starlette: Where is uploaded file through form request?

Created on 3 Jan 2020  路  3Comments  路  Source: encode/starlette

Hi,
I'm trying to upload audio to my Starlette server but I can not get the path of the audio file.

In document I could find how to get original file name and read contents but I could not find how to get file path of temporary file.

form = await request.form()
filename = form["upload_file"].filename
contents = await form["upload_file"].read()

Or how can i use write method?
How can I specify the location to save the data?

Could you give me a hint?

Thanks in advance.

Most helpful comment

@kouohhashi
you can make this as usual, like this:

with open('/any/file/path/you/want', 'w') as f:
     f.write(contents)

I tried but it did not work. I figured out that mode need to be 'wb'.
with open('/any/file/path/you/want', 'wb') as f:
f.write(contents)

All 3 comments

@kouohhashi
you can make this as usual, like this:

with open('/any/file/path/you/want', 'w') as f:
     f.write(contents)

Thanks @annndrey.

The uploaded file may or may not actually have a location on disk, since it could be in-memory, since we use Python SpooledTemporaryFile which only starts writing to disk once the file becomes large enough.

You can take a look here: https://github.com/encode/starlette/blob/5f4fc85541f44013d1ed40fb77eb772db50fe02b/starlette/datastructures.py#L420

I think you can use ifform["upload"].file.name` to check if the file is on disk on not.

@kouohhashi
you can make this as usual, like this:

with open('/any/file/path/you/want', 'w') as f:
     f.write(contents)

I tried but it did not work. I figured out that mode need to be 'wb'.
with open('/any/file/path/you/want', 'wb') as f:
f.write(contents)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Immortalin picture Immortalin  路  3Comments

jordic picture jordic  路  6Comments

jordic picture jordic  路  4Comments

PeriGK picture PeriGK  路  5Comments

cw-andrews picture cw-andrews  路  4Comments