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

Time:09-01

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?

CodePudding user response:

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

CodePudding user response:

Referring to the Django documentation, this code can be used after receiving the file:

def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb ') as destination:
    for chunk in f.chunks():
        destination.write(chunk)

If you want to save it to the database, u should just create object of your model, for example:

file = request.FILES["uploaded_file"]
save_file = File.objects.create(
                                name=file.name,
                                file=file
                               )

To download file u need a path to that file.

file_path = save_file.file.path
  • Related