nloding Posted May 28, 2008 Share Posted May 28, 2008 GMail is the best example I know of; a document, say a PDF file, is listed with a 'view' and a 'download' link immediately after. When you click 'view', it opens as you would expect (in your browser, for instance). If you click 'download', then the file download prompt is automagically brought up. How? I have a site I'm working on with an archived documents section. I want this option available. How? HOW? I've tried Googling it, but if you put the word 'download' in your search, you don't get anywhere. Quote Link to comment Share on other sites More sharing options...
nloding Posted May 28, 2008 Author Share Posted May 28, 2008 SOLVED! I found it, here's the code for those who are interested: Markup: <a href="#" onclick="downloadFile('20')">download</a> <script type="text/javascript"> function downloadFile(id) { var url = 'http://mywebsite.com/downloadfile.php?id=" + id; var tempWindow = window.open(url); } </script> Server-side (downloadfile.php) <?php $id = $_GET['id']; // however you find your filename and path, do it here, i used a mysql query $filename = str_replace(" ", "_", $result['filename']); $path = "/path/to/" . $result['filename']; Header("Content-type: application/octet-stream"); Header("Content-length: " . filesize($path)); Header("Content-Disposition: attachment; filename=" . $filename); $fp = fopen($path, 'rb'); fpassthru($fp); fclose($fp); ?> Quote Link to comment Share on other sites More sharing options...
haku Posted May 29, 2008 Share Posted May 29, 2008 The javascript is unnecessary for this. You can use a force download script (I use this one, and in your anchor, you just put a link to the download script. You will have to add something to tell the script which file it is you want downloaded however. Quote Link to comment Share on other sites More sharing options...
nloding Posted May 29, 2008 Author Share Posted May 29, 2008 The Javascript is necessary to open a new window instead of directing them away from the current page. Thank you for the link, though; I'm now having issues with IE -- it can view the doc, but not download. I'll look at this script -- thanks! Quote Link to comment Share on other sites More sharing options...
haku Posted May 29, 2008 Share Posted May 29, 2008 The download script I gave you wont nagivate them away from the page. It just pops up a 'open', 'save', 'cancel' window. Good luck! Quote Link to comment Share on other sites More sharing options...
nloding Posted May 29, 2008 Author Share Posted May 29, 2008 It still refreshes the page at the very least. I'd rather not go that route. However, that script worked beautifully. I'm modding it right now to make it fit my entire site. Thanks for that link. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.