我正在尝试创建一个docx文件并将其发送到前端客户端应用程序,以便可以将其下载到用户的本地计算机。我使用 FastAPI 作为后端。我还使用python-docx库来创建Document.
下面的代码用于创建一个docx文件并将其保存到服务器。
@app.post("/create_file")
async def create_file(data: Item):
document = Document()
document.add_heading("file generated", level=1)
document.add_paragraph("test")
document.save('generated_file.docx')
return {"status":"Done!"}
Run Code Online (Sandbox Code Playgroud)
然后使用以下代码将创建的docx文件作为 a发送FileResponse到客户端。
@app.get("/generated_file")
async def download_generated_file():
file_path = "generated_file.docx"
return FileResponse(file_path, media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document', filename=file_path)
Run Code Online (Sandbox Code Playgroud)
在客户端(我正在使用 ReactJS):
@app.post("/create_file")
async def create_file(data: Item):
document = Document()
document.add_heading("file generated", level=1)
document.add_paragraph("test")
document.save('generated_file.docx')
return {"status":"Done!"}
Run Code Online (Sandbox Code Playgroud)
调用函数generated.docx时会下载文件。downloadFile但是,该docx文件始终已损坏并且无法打开。我尝试使用txt文件,效果很好。我需要使用docx文件,我该怎么办?