admin管理员组

文章数量:1291088

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 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?

Share Improve this question asked Jun 14, 2017 at 22:54 Diriector_DocDiriector_Doc 6103 gold badges14 silver badges29 bronze badges 3
  • Is there at least a way to change the value of download="name"? – Diriector_Doc Commented Jun 14, 2017 at 23:00
  • Ok, thanks for your help. – Diriector_Doc Commented Jun 14, 2017 at 23:04
  • @Dijkgraaf how is downloading a file a security hole? – David Álvarez Commented Jun 14, 2017 at 23:17
Add a ment  | 

2 Answers 2

Reset to default 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.

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/72qepvng/

本文标签: Custom download name with Javascript or JQueryStack Overflow