in HTML, but I am afraid that this ...">

Custom Download Name with Javascript or JQuery

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

I would like to have a download link that (unsurprisingly) download the file. I would also like a text box to appear on the screen that allows the user to name the file that thay downloads.

The site will look something like this:

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

I want the block to <button>use onclick"function()"to upload a file. The function will receive text from the text field and will use it to indicate the file when it is loaded. I need help finding a way to name a file using Javascript or JQuery just like download="name".

I was looking for a while to do this, but no luck. Is this project possible? If so, how is this done?

+4
source share
2 answers

Well, you can do this by creating the element adynamically and setting the entered name as an attribute download:

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 works Demo and you can check my answer for uploading a file using JavaScript.

+2
source

Of course. Let it dynamically add a hidden link to the page and click on it, thereby 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 in Chrome): https://jsfiddle.net/72qepvng/

0

Source: https://habr.com/ru/post/1679301/


All Articles