-2

I use python 3.6 Django, my code looks like this:

from docx import Document

document = Document()
document.add_heading('My docx', 0)
document.save('myFile.docx')

return HttpResponse(document, content_type='application/vnd')

I don't want to save it on server, instead I want to send it to client side using ajax and save it on client pc. Any thoughts how to do it?

Nesi
  • 19
  • 5

1 Answers1

0

I was never in touch with ajax but I know how to present your file as a download without saving it in more as a temporary buffer.

You did not present the full function or method of your code. Therefore I am giving a get() method of a class-based view as an example.

Try this:

import io
from django.http import FileResponse

def get(self):
    document = Document()
    document.add_heading('My docx', 0)
    
    buffer = io.BytesIO()  # create buffer
    doc.save(buffer)  # save doc to buffer
    buffer.seek(0)   # returns the curser to the beginning of the bytestream
    return FileResponse(buffer, as_attachment=True, filename=f"your_file.docx")

Read more about FileResponse here.

Tarquinius
  • 1,468
  • 1
  • 3
  • 18
  • how to handle it on client side? – Nesi Jan 12 '23 at 13:59
  • As you only presented a snippet of a function of your code you need to integrate that yourself. But theoretically: if a user, maybe by pressing a button, gets presented your proposed `HttpResponse`, now, the same button should present the `FileResponse` – Tarquinius Jan 12 '23 at 14:02
  • How to save this buffer using javascript? I get it on client side. – Nesi Jan 12 '23 at 14:05
  • There is no need to use javascript. Just wire up that view, go to its url and your browser will open up a download option. You just need to present a button that leads the user to your view e.g. its url. Can't help you better without seeing more of your code. – Tarquinius Jan 12 '23 at 14:09
  • :D I have no idea what you describe... it uses javascript to send this request to server and django produces this buffer. Afterwards the response returns to front end to javascript. – Nesi Jan 12 '23 at 14:14