javascriptpythonpython-3.xdjangodjango-file-upload

How to convert bytes into a file the user can download in Django?


I have the bytes of a file saved in my Django database. I want users to be able to download this file.

My question is how do I convert bytes into an actual downloadable file. I know the file name, size, bytes, type and pretty much everything I need to know.

I just need to convert the bytes into a downloadable file. How do I do this?

I don't mind sending the file bytes over to the front-end so that JavaScript could make the file available to download. Does anyone know how to do this in JavaScript?


Solution

  • If you check Django documentation:

    Django request-response

    There is a class that is FileResponse

    FileResponse(open_file, as_attachment=False, filename='', **kwargs)
    

    FileResponse is a subclass of StreamingHttpResponse optimized for binary files.

    it accepts file-like object like io.BytesIO but you have to seek() it before passing it to FileResponse.

    FileResponse accepts any file-like object with binary content, for example a file open in binary mode like so:

       from django.http import FileResponse
       import io
    
       buffer = io.BytesIO(file)
       buffer.seek(0)
       response = FileResponse(buffer, as_attachment=True, filename='filename.foo')