0

I searched a lot but couldn't find a solution I thank anyone who can help me.

I want to download files on button click but based on values in the text of buttons.

I have three buttons in my HTML like this

<input type="button" onclick="myFunction(this, name1.mp3)" value="button1.mp3">
<input type="button" onclick="myFunction(this, name2.mp3)" value="button2.mp3">
<input type="button" onclick="myFunction(this, name3.mp3)" value="button3.mp3">

my JavaScript is

function myFunction(elmnt, name) {
  var url = "http://mysite*com/" + elmnt.value;
  var downloadFileWithThisName = name;

  ---my download code---


}

How can I download my url with the name I passed to function?

what should I write for ---my download code--- part?

Thank you in advance.

Lord Tesla
  • 84
  • 6
  • Does this answer your question? [How to trigger a file download when clicking an HTML button or JavaScript](https://stackoverflow.com/questions/11620698/how-to-trigger-a-file-download-when-clicking-an-html-button-or-javascript) – Akash Shrivastava Feb 21 '20 at 09:01

2 Answers2

1
function myFunction(elmnt, name) {
  var url = "http://mysite*com/" + elmnt.value;
  const a = document.createElement('a');
      a.href = url;
      a.download = name; // here you can specify your filename
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
}
Vishnu Shenoy
  • 862
  • 5
  • 18
0

What you could do is to dynamically create an A element, add the 'download' attribute, set the Href and click it, all in code. Then remove it from the DOM.

The best answer judging for your code is shown here: https://stackoverflow.com/a/42696866/1891140

var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

But you also can do it by using a simple JQUERY:

$("<a href='"+url+"' download class='hidden-a'></a>").appendTo("body");
$(".hidden-a")[0].click();
Mannyfatboy
  • 389
  • 7
  • 14