Jump to content

What do I use as input type to create a file save dialog?


TonyC

Recommended Posts

The syntax <input type="file"> is used to create a file open button and dialog box.  What can I use to create a file save dialog box?  Using HTML5, CSS3, and JavaScript (no libraries). 

Thank you 

 

Link to comment
Share on other sites

With pure Javascript there's a window method called saveAs() which isn't widely supported by browsers. I can't see any reference to this method on the MDN so I'm not even certain if it's a standard. Somebody built an example with a cross-browser polyfill here: https://codepen.io/davidelrizzo/pen/cxsGbI It's not exactly a library, just a fallback function that's used if the browser doesn't have native support.

If you have a server-side language available you can submit a form to an invisible iframe, have the server generate the data and serve it with a "Content-Disposition: attachment" header. Here's a very simple PHP example:

<form action="save-file.php" method="POST" target="filesaver">
  <div>
    <label>Filename: <input type="text" name="filename"></label>
    <label>File content:
      <textarea name="data"></textarea>
    </label>
    <button type="submit">Save</button>
  </div>
</form>
<iframe name="filesaver" width="1" height="1" frameborder="0"></iframe>
<?php
// This is save-file.php
$data = $_POST['data'];
$filename = $_POST['filename'];
header('Content-Disposition: attachment; filename="' . $filename . '"');
echo $_POST['data'];
?>

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...