Starting File Download with JavaScript

starting file download with JavaScript

Try this lib https://github.com/PixelsCommander/Download-File-JS it`s more modern than all solutions described before because uses "download" attribute and combination of methods to bring best possible experience.

Explained here - http://pixelscommander.com/en/javascript/javascript-file-downliading-ignore-content-type/

Seems to be ideal piece of code for starting downloading in JavaScript.

Start File Download via Javascript

Create an element without attaching it to any parent element so it is invisible to the user, and click it in JS.

link = document.createElement("a"); //create 'a' element
link.setAttribute("href", "file"); //replace "file" with link to file you want to download
link.setAttribute("download", "file");// replace "file" here too
link.click(); //virtually click <a> element to initiate download

The client will still be able to see the URL in the javascript code if they wanted, but the link is invisible.

Download File Using JavaScript/jQuery

Use an invisible <iframe>:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = url;
};
</script>

To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me or alternatively application/octet-stream, which is used for arbitrary binary data.

If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target attribute set to _blank.

In jQuery:

$('a#someID').attr({target: '_blank', 
href : 'http://localhost/directory/file.pdf'});

Whenever that link is clicked, it will download the file in a new tab/window.

How to trigger a file download when clicking an HTML button or JavaScript

For the button you can do

<form method="get" action="file.doc">
<button type="submit">Download!</button>
</form>

Initiate file download in browser from JavaScript

I asked you if you have the full URL to the file.
If you want to start the download from a link, use the solution Kielstra provided. If you want to start the download using javascript, use the following code:

window.location = url_to_file;

How to download file with javascript?

You can provide the link to this function to download the file :

function downloadURI(uri, name) 
{
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}


Related Topics



Leave a reply



Submit