starlette icon indicating copy to clipboard operation
starlette copied to clipboard

Where is uploaded file through form request?

Open kouohhashi opened this issue 6 years ago • 3 comments

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.

kouohhashi avatar Jan 03 '20 13:01 kouohhashi

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

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

annndrey avatar Feb 15 '20 18:02 annndrey

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 if form["upload"].file.name` to check if the file is on disk on not.

lovelydinosaur avatar Feb 17 '20 10:02 lovelydinosaur

@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)

solankydev avatar Jun 29 '20 12:06 solankydev