Jump to content

How do they do it? A 'view' and 'download' link!


nloding

Recommended Posts

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.

Link to comment
Share on other sites

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);
?>

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.