Download File Using jQuery

2019-01-01 12:09发布

How can I prompt a download for a user when they click a link.

For example, instead of:

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

I could use:

<a href="#">Download Here</a>

 $('a').click... //Some jquery to download the file

This way, Google does not index my HREF's and private files.

Can this be done with jQuery, if so, how? Or should this be done with PHP or something instead?

10条回答
高级女魔头
2楼-- · 2019-01-01 12:41

By stating window.location.href = 'uploads/file.doc'; you show where you store your files. You might of course use .htacess to force the required behaviour for stored files, but this might not always be handful....

It is better to create a server side php-file and place this content in it:

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$_REQUEST['f']);
readfile('../some_folder/some_subfolder/'.$_REQUEST['f']); 
exit;

This code will return ANY file as a download without showing where you actually store it.

You open this php-file via window.location.href = 'scripts/this_php_file.php?f=downloaded_file';

查看更多
冷夜・残月
3楼-- · 2019-01-01 12:41

See here for a similar post on using jQuery to clear forms: Resetting a multi-stage form with jQuery

You may also be running into an issue where the values are being repopulated by the struts value stack. In other words, you submit your form, do whatever in the action class, but do not clear the related field values in the action class. In this scenario the form would appear to maintain the values you previously submitted. If you are persisting these in some way, just null each field value in your action class after persisting and prior to returning SUCCESS.

查看更多
若你有天会懂
4楼-- · 2019-01-01 12:43

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';
查看更多
心情的温度
5楼-- · 2019-01-01 12:45
 var link=document.createElement('a');
 document.body.appendChild(link);
 link.href=url;
 link.click();
查看更多
唯独是你
6楼-- · 2019-01-01 12:46

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.

查看更多
若你有天会懂
7楼-- · 2019-01-01 12:49
  • Using jQuery function

        var valFileDownloadPath = 'http//:'+'your url';
    
       window.open(valFileDownloadPath , '_blank');
    
查看更多
登录 后发表回答