Search code examples
pythonpostaiohttp

How do you extract a file from an incoming POST


I have a strange case where I have a POST coming in with a file attached. I am using aiohttp as a server. Normally I would use a get to retrieve a file but that’s not possible in this situation. I can’t seem to find any documentation on retrieving a file over http using aiohttp.


Solution

  • Simple example assuming you've used a form with enctype="multipart/form-data":

    async def handle_file_upload(request):
        data = await request.post()
        print('parts:', data.keys())
        # assuming we have a file called foobar
        print('filename:', data['foobar'].filename)
        print('file object:', data['foobar'].file)
        print('file content:', data['foobar'].file.read())
        ...  # (return response etc.)
    

    be careful about using code like this in the wild with no protection as I believe await request.post() will read all request data into memory. If someone does curl -X POST --data-binary "@/dev/urandom"... you'll be in big trouble.