Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom download name with Javascript or JQuery

Tags:

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?

like image 723
Diriector_Doc Avatar asked Jun 14 '17 22:06

Diriector_Doc


People also ask

How do I trigger a download when clicking HTML button or JavaScript?

Method 1: How to Trigger a File Download by Clicking an HTML Button? You need to utilize the <input> tag to create an HTML button and set its value to “Download”. The value is a user-defined attribute and can be set as per the user's wish. The script executes in the test.

How do I use JavaScript download?

Summary. The download() function is used to trigger a file download from JavaScript. It specifies the contents and name of a new file placed in the browser's download directory. The input can be a String, Blob, or Typed Array of data, or via a dataURL representing the file's data as base64 or url-encoded string.


1 Answers

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.

like image 165
cнŝdk Avatar answered Oct 10 '22 08:10

cнŝdk