代码之家  ›  专栏  ›  技术社区  ›  lejahmie

在网站上自动开始下载文件?

  •  1
  • lejahmie  · 技术社区  · 16 年前

    当用户单击链接时,如何自动启动文件进行下载?

    就像在www.iStockphoto.com上一样

    2 回复  |  直到 16 年前
        1
  •  2
  •   Quentin    16 年前
    <a href="path-to-file.jpeg">link</a>
    

    连同 content-disposition 使其成为附件的标题。

        2
  •  1
  •   lejahmie    16 年前

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

    创建一个名为 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()