Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download File Using jQuery

People also ask

How can download PDF with button click in jQuery?

Downloading PDF File on Button Click using jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).


I might suggest this, as a more gracefully degrading solution, using preventDefault:

$('a').click(function(e) {
    e.preventDefault();  //stop the browser from following
    window.location.href = 'uploads/file.doc';
});

<a href="no-script.html">Download now!</a>

Even if there's no Javascript, at least this way the user will get some feedback.


If you don't want search engines to index certain files, you can use robots.txt to tell web spiders not to access certain parts of your website.

If you rely only on javascript, then some users who browse without it won't be able to click your links.


Here's a nice article that shows many ways of hiding files from search engines:

http://antezeta.com/news/avoid-search-engine-indexing

JavaScript isn't a good way not to index a page; it won't prevent users from linking directly to your files (and thus revealing it to crawlers), and as Rob mentioned, wouldn't work for all users.
An easy fix is to add the rel="nofollow" attribute, though again, it's not complete without robots.txt.

<a href="uploads/file.doc" rel="nofollow">Download Here</a>

 var link=document.createElement('a');
 document.body.appendChild(link);
 link.href=url;
 link.click();

Yes, you would have to change the window.location.href to the url of the file you would want to download.

window.location.href = 'http://www.com/path/to/file';

  • Using jQuery function

        var valFileDownloadPath = 'http//:'+'your url';
    
       window.open(valFileDownloadPath , '_blank');