I am trying to create a docx file and send it to the frontend client app, so that it can be downloaded to the user's local machine. I am using FastAPI for the backend. I am using python-docx library also to create the Document.
The code below is used to create a docx file and save it to the server.
@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!"}
The below code is then used to send the created docx file as a FileResponse to the client.
@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)
On Client side (I am using 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();
});
};
The generated.docx file gets downloaded when downloadFile function is called. However, the docx file is always corrupted and doesn't open. I tried using txt file and it works fine. I need to use docx file, so what can I do?