Starlette: Documentation: File upload examples

Created on 22 Mar 2019  路  3Comments  路  Source: encode/starlette

Some more examples for file uploads and handling would greatly improve documentation.

Most helpful comment

Do you think you can add a few more lines for disk IO? I.e. save the file to disk. Would save a lot of time debugging and dumping metadata.

All 3 comments

The quite good docs is here https://www.starlette.io/requests/#request-files

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

Is it not enough?

Do you think you can add a few more lines for disk IO? I.e. save the file to disk. Would save a lot of time debugging and dumping metadata.

I published a filestorage library for handling uploads to a local folder or an S3 bucket, with either sync or async operations supported.

@app.route('/upload', methods=['GET', 'POST'])
async def upload(request):
    template = "upload.html"
    context = {"request": request}
    if request.method == 'GET':
        return templates.TemplateResponse(template, context)
    form = await request.form()
    context['uploaded_filename'] = await store.async_save_field(form['file'])
    return templates.TemplateResponse(template, context)

...

if __name__ == "__main__":
    store.handler = AsyncLocalFileHandler(
        base_path='uploads', filters=[RandomizeFilename()], auto_make_dir=True,
    )
    store.finalize_config()

    uvicorn.run(app, host='0.0.0.0', port=8000)

And in the template:

<form action="upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <br>
  <input type="submit"/>
</form>
Was this page helpful?
0 / 5 - 0 ratings

Related issues

gnat picture gnat  路  6Comments

hyperknot picture hyperknot  路  6Comments

MarcDufresne picture MarcDufresne  路  6Comments

kouohhashi picture kouohhashi  路  3Comments

cw-andrews picture cw-andrews  路  4Comments