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

I want to make a website that lets the user upload a file and then make the file available to be downloaded by another user.

The code to convert the uploaded file to bytes is done (used uploadedFile.read()). I also plan to save the bytes of the file to the database instead of the actual file, for example:

uploadedFile = request.FILES["file"]

file_data = uploadedFile.read()

# Save file_data to database here...

How do I convert the file bytes to an actual downloadable file? (basically the opposite of file.read() in Django)

Does anyone know how to do this, and please edit this question or ask if anything is unclear. Thank you.

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

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')
Back to Top