Luiz
Luiz

Reputation: 108

How to get downloaded file name inserted by the user?

In my JavaScript, I'm using an <a> tag with the download attribute to let the user download a generated file. I can set a default name for the file, however the user might change it before they save it to their system. Is there a way I can get the name that the user wrote in the save dialog?

The main reason for this is so that I can use the same name again as the default when the user goes to download the file again.

Here's the code:

var json = JSON.stringify(currentProject, null, '\t');

var a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([json], {type: 'text/json'}));
a.download = currentProjectName;

a.click();

If it isn't possible to do this with the <a> tag method, I would like to know of some other download method that allowed for this, in some way.

Upvotes: 3

Views: 909

Answers (1)

BJT
BJT

Reputation: 658

I do not think you can do that without custom made client for the end-user, save dialog is controlled by OS, but you could offer to the user that he renames file while in your application something like this: working code on repl.it

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Download</title>
</head>

<body>
  <div>
    <input type="text" id="filename-input" value="">
    <a id="download" href="generated-filename.txt" download>Download</a>
  </div>
  <script>
    document.addEventListener('DOMContentLoaded', loadDefaultFilename, false);

    function loadDefaultFilename() {
      // this could be value from database or cookie
      let userDefaultFilename = localStorage.getItem('default-filename') || 'generared-file.txt';

      let filenameInput = document.getElementById('filename-input');
      let fileDownloadLink = document.getElementById('download');
      fileDownloadLink.setAttribute('href', userDefaultFilename)
      // load default filename from somewhere, e.g database or cookie

      // set the default name
      filenameInput.value = userDefaultFilename;
    }


    let button = document.getElementById('download');
    button.addEventListener('click', function(e) {
      const defaultFilename = document.getElementById('filename-input').value;
      saveDefaultFilename(defaultFilename);
    });

    function saveDefaultFilename(filename) {
      localStorage.setItem('default-filename', filename);
      console.log(filename);
    }
  </script>
</body>

</html>

Upvotes: 2

Related Questions