2

Good day. Today I'm trying to send a document generated on the server to the user on the click of a button using Flask.

My task is this: Create a document (without saving it on the server). And send it to the user. However, using a java script, I track the button click on the form and use fetch to make a request to the server. The server retrieves the necessary data and creates a Word document based on it. How can I form a response to a request so that the file starts downloading?

Code since the creation of the document. (The text of the Word document has been replaced) python Falsk:

document = Document()
document.add_heading("Some head-title")
document.add_paragraph('Some text')
f = BytesIO()
document.save(f)
f.seek(0)
return send_file(f, as_attachment=True, download_name='some.docx')

However, the file does not start downloading.

How can I send a file from the server to the user?

Edits

This is my js request.

fetch('/getData', {
    method : 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        someData: someData,
    })
})
.then(response => 
    response.text()
)
.then(response =>{
    console.log(response);
});

This is my html

<form action="" name="getData" method="post" enctype="multipart/form-data">
<button type = "submit" name = "Download">Download</button>
</form>

1 Answers1

3

You need to specify the mimetype, It tries to detect the mimetype from the filename but since we are not saving it we need to specify the mimetype.

return send_file(f, mimetype='application/msword', as_attachment=True, download_name='output.doc')

darth baba
  • 1,277
  • 5
  • 13
  • Thanks for the answer, I tried your advice, but I still don't get the effect I want (download to a local computer). I've updated my question to clarify the point of the request. Maybe I'm doing something wrong, could you take a look? @darth baba – Sherlock_201 Feb 17 '23 at 20:29