自动启动网站上的文件下载?

时间:2010-02-23 14:56:38

标签: html file user-interface download

当用户点击链接时,如何自动启动文件以供下载? 例如,当用户单击允许他们下载图像的链接时。

喜欢它适用于www.iStockphoto.com

2 个答案:

答案 0 :(得分:2)

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

content-disposition标题一起使其成为附件。

答案 1 :(得分:1)

这是我正在寻找的答案。希望它能帮助其他人寻找答案。

创建一个名为 downloadfile.php 的文件,并添加以下内容;

$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;
    }

然后你可以像这样添加一个指向该文件的链接:

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

当然这只是一个例子。它可以以各种方式完成。要记住的重要语法是header()和readfile()