Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to 'simulate' right-click save-as command or force download of file in the browser with JavaScript?

I have this situation where we have media files stored on a global CDN. Our web app is hosted on it's own server and then when the media assets are needed they are called from the CDN url. Recently we had a page where the user can download file attachments, however some of the file types were opening in the browser instead of downloading (such as MP3). The only way around this was to manually specify the HTTP response to attach the file but the only way I could achieve this was to download the file from CDN to my server and then feed it back to the user, which defeats the purpose of having it on the global CDN. Instead I am wondering if there is some client side solution for this?

EDIT: Just found this somewhere, though I'm not sure if it will work right in all the browsers?

<body>
<script>
function downloadme(x){
myTempWindow = window.open(x,'','left=10000,screenX=10000');
myTempWindow.document.execCommand('SaveAs','null','download.pdf');
myTempWindow.close();
}
</script>

<a href=javascript:downloadme('/test.pdf');>Download this pdf</a>
</body>

RE-EDIT: Oh well, so much for that idea -> Does execCommand SaveAs work in Firefox?

like image 441
MetaGuru Avatar asked Sep 14 '10 17:09

MetaGuru


People also ask

How does HTTP file download work?

Hypertext Transfer Protocol (HTTP) downloads use the same protocol as browsing websites to send the file data. It is the most popular way to download files from the internet. All web browsers use this to download files directly. HTTP does not support pausing or resuming failed downloads natively.


2 Answers

Does your CDN allow you to specify the HTTP headers? Amazon cloudfront does, for example.

like image 116
Lou Franco Avatar answered Oct 06 '22 23:10

Lou Franco


I found an easy solution to this that worked for me. Add a URL parameter to the file name. This will trick the browser into bypassing it's built in file mappings. For examaple, instead of http://mydomain.com/file.pdf , set your client side link up to point to http://mydomain.com/file.pdf? (added a question mark)

like image 32
user3334305 Avatar answered Oct 06 '22 23:10

user3334305