【问题标题】:How to save python docx on client side using ajax?如何使用ajax在客户端保存python docx?
【发布时间】:2023-01-12 21:45:32
【问题描述】:
我使用 python 3.6 Django,我的代码如下所示:
from docx import Document
document = Document()
document.add_heading('My docx', 0)
document.save('myFile.docx')
return HttpResponse(document, content_type='application/vnd')
我不想将它保存在服务器上,而是想使用 ajax 将它发送到客户端并将其保存在客户端电脑上。
任何想法如何去做?
【问题讨论】:
标签:
python
html
django
ajax
python-docx
【解决方案1】:
我从来没有接触过 ajax,但我知道如何将您的文件显示为下载而不将其保存为临时缓冲区。
您没有提供代码的全部功能或方法。因此,我以基于类的视图的 get() 方法为例。
尝试这个:
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")
阅读更多关于FileResponsehere的信息。