I have a NGINX+Flask+KnockoutJS single page app and I want to create a download button that allow the user to download the data he/she is visualising and manipulating client side without reloading the full page There are a number of pure JavaScript solutions (like download.js) but none of them is fully compatible with all major browsers (e.g. Safari).
Basically what I would like to have is:
Is it possible?
Is it possible?
Of course. Let's have an example:
- The app shows a table to the user
You mean, something along the lines of using a <table>
tag:
<table>
<tr>
<td>Foo bar</td>
<td>123</td>
<td>
<form action="/download/foo/bar/123" method="post">
<button type="submit" value="Download foo bar 123" />
</form>
</td>
</tr>
... here come some other rows of the table ...
</table>
- The user push the download button
OK, this one is obvious. The user submits the form by clicking on the corresponding submit button on the desired row of your table.
- JavaScript sends data to a server side endpoint
Why care about javascript when you have standard HTML forms which can submit data to the server in a purely browser agnostic manner, like shown in point 1.? And if you really cared about some javascript you could always subscribe to the onsubmit
action of the <form>
I showed earlier and inject the necessary data as hidden fields into the DOM using javascript.
- The server generate the file on the fly based on the data sent from the client
Yeah, that's like standard HTTP protocol. The server will simply handle the /download/foo/bar/123
endpoint and simply send the file as attachment:
HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Length: 29
Content-Disposition: attachment; filename=foobar123.bin
HERE COMES THE BINARY CONTENT
- The browser open the download/save as dialog
That's exactly what any browser's gonna do when it handles the previously shown HTTP response from a server.
Conclusion: The HTTP protocol and standard HTML forms already provide you with the necessary tools to achieve your requirements. And if you wanted a little bit of additional fanciness, just enhance the HTML form upon submission using javascript in order to append any required fields as hidden input elements that you would like to send to the server. And then leave it to the browser to handle the download.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With