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.

1

2 Answers 2

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); } 
Sign up to request clarification or add additional context in comments.

Comments

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(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.