0

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?

  • Any reason not to just write the bytes to the client as an "application/x" attachment for the user to open with the appropriate app and save if he wants to? – nigel222 Aug 31 '22 at 12:50
  • Well prefably I would like to know a way to turn the bytes into a file the user can download @nigel222 –  Aug 31 '22 at 13:03
  • "_bytes of a file saved in my Django database_" please don't do that. Databases should not be used to store files. See [Should binary files be stored in the database?](https://dba.stackexchange.com/questions/2445/should-binary-files-be-stored-in-the-database) – Abdul Aziz Barkat Aug 31 '22 at 14:12
  • After researching a bit I agree with you, the only problem I have is how do I encrypt the file with Django so viruses and other malware cannot destroy my website? @AbdulAzizBarkat –  Aug 31 '22 at 15:10

2 Answers2

0

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
Karol
  • 116
  • 2
  • The problem is that there is much less freedom encrypting the file this way which means I want to save the file as encrypted bytes string. I don't know how to convert the bytes string into a downloadable file. –  Aug 31 '22 at 12:22
0

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')
jcremona
  • 28
  • 6