开发者

Autostart download of file on website?

开发者 https://www.devze.com 2022-12-21 04:17 出处:网络
How do i automaticly start a file for download when a user clicks a link? For example when a user click开发者_JAVA技巧s a link that allows them to download a image.

How do i automaticly start a file for download when a user clicks a link? For example when a user click开发者_JAVA技巧s a link that allows them to download a image.

Like it works on www.iStockphoto.com


<a href="path-to-file.jpeg">link</a>

Along with a content-disposition header that makes it an attachment.


Here is the answer I was looking for. Hopefully it will help other people looking for an answer.

Create a file called downloadfile.php for example and add the following;

$file = $_GET['file'];
if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }

Then you can add a link to that file like this:

<a href="downloadfile.php?file=dog.jpg">Download image!</a>

Of course this is just an example. It can be done in various ways. Important syntaxes to remember are header() and readfile()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号