python-3.xsanic

How to perform file upload in Sanic


I am trying to perform file upload on Sanic but it is not working properly, the normal syntax for flask doesn't seem to work well with sanic here.

I can't access even the filename or the save method to save the uploaded file to a given directory.


Solution

  • After a long struggle I found the following code to be working

    @app.route("/upload", methods=['POST'])
    async def omo(request):
        from sanic import response
        import os
        import aiofiles
        if not os.path.exists(appConfig["upload"]):
            os.makedirs(appConfig["upload"])
        async with aiofiles.open(appConfig["upload"]+"/"+request.files["file"][0].name, 'wb') as f:
            await f.write(request.files["file"][0].body)
        f.close()
    
        return response.json(True)