6

I know how to use the <a href="file.jpg" download="name"> block in HTML, but I'm afraid that will not work for this project.

I would like to have a download link which will (unsurprisingly) download a file. I would also like a text box on the screen that will allow the user to name the file that thay download.

The site would look something like this:

Name:<input type="text" name="Name" value="Custon Name">
<br>
<button type="button">Download</button>

I want the <button> block to use onclick"function()" in order to download the file. The function will get the text from the text box and use it to name the file when downloading it. The thing I need help with is finding a way to name the file using Javascript or JQuery in the same way that download="name" would.

I've looked for a while for a way to do this, but no luck. Is this project possible? If so, how is it done?

Diriector_Doc
  • 582
  • 1
  • 12
  • 28

2 Answers2

6

Well you can do it by creating the a element dynamically and setting the inputted name as its download attribute:

function downloadIt() {
  var name = document.getElementsByName("Name")[0].value;
  if (name && name !=='') {
    var link = document.createElement('a');
    link.download = name;
    link.href ="file.png";  
    link.click();
  }
}

This is a working Demo and you can check my answer for file download with JavaScript too.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

Sure you can. Let's add a hidden link in the page dynamically and click on it, thus emulating the effect of the "download" attribute.

HTML:

Name:<input type="text" name="Name" id="myName" value="Custom Name">
<br>
<button type="button" onclick="download()">Download</button>

JS:

function download() {
  var a = document.createElement("a");
  a.href = "myfile.png";
  a.download = document.getElementById("myName").value;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

Working example (tested on Chrome): https://jsfiddle.net/72qepvng/