Download file from server with Flask and JS Download file from server with Flask and JS flask flask

Download file from server with Flask and JS


You can do the below

return send_from_directory(dir, file_name, as_attachment=True)

This will download the file on the user's machine.

Edit:

BTW, if you create an html form like below, you do not need javascript.

<form action='action here' method='post'>    <input type='submit'></form>


As @clockwatcher mentioned a different question, I used the download.js module to handle the download of the image.

So my JS code looks like this now:

function make_image(text){    const json={        text: text    };    const options={        method: "POST",        body: JSON.stringify(json),        headers:{            'Content-Type':'application/json',        }    };    fetch('/image',options)        .then(res=>{            return res.blob();        }).then(blob=>{            download(blob)        }).catch(err=>console.log(err));}

And an addition to the script tag in the html:

<script src="https://cdnjs.cloudflare.com/ajax/libs/downloadjs/1.4.8/download.min.js"></script>

With no change in the Python server code.

It works now