我试图创建一个
以下代码用于将创建的docx文件作为FileResponse发送给客户端。
客户端(我正在使用ReactJS):
当调用
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!"}
以下代码用于将创建的docx文件作为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)
客户端(我正在使用ReactJS):
createFile = async () => {
const data = {
start: this.state.start,
end: this.state.end,
text: this.state.text,
};
await axios.post("http://localhost:8000/create_file", data).then(() => {
console.log("processing completed!");
});
};
downloadFile = async () => {
await axios.get("http://localhost:8000/generated_file").then((res) => {
const url = URL.createObjectURL(new Blob([res.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "generated.txt");
link.click();
});
};
当调用
downloadFile
函数时,会下载generated.docx
文件。然而,docx 文件总是损坏的,无法打开。 我尝试使用txt文件,它可以正常工作。我需要使用docx文件,那我该怎么办?
Response
来避免这种情况。请参阅此处和此处,以及此、此和此答案。 - Chris