【问题标题】:How can I allow users to download pictures (.gif,.png,.jpeg)?如何允许用户下载图片(.gif、.png、.jpeg)?
【发布时间】:2012-08-16 07:05:11
【问题描述】:

如何允许用户下载保存在服务器上的图片?目标是让用户单击链接并获得指定的图像以开始下载。

Facebook 示例:

【问题讨论】:

    标签: php javascript image file download


    【解决方案1】:

    链接到另一个 .php 页面,而不是图像。然后在该页面上使用 content-disposition 标头,如下所示:

    <?php
    // Define the name of image after downloaded  
    header('Content-Disposition: attachment; filename="file.jpg"');  
    
    // Read the original image file  
    readfile('file.jpg');  
    ?>  
    

    从那里,您可以在 get 命令中添加图像的文件名,例如

    `download.php?filename=file` 
    

    然后在文件中将其引用为:

    readfile($_GET['filename'].'.jpg')
    

    【讨论】:

    • 很好的答案,但请在传递给readfile 之类的东西之前始终清理$_GET(上面将允许我在您的服务器上下载任何以“.jpg”结尾的文件”,可能还有其他一些工作)。也许您知道这一点,但为了简洁而省略了它,但其他人可能会照搬您的示例,并在他们的服务器中引入一个很大的安全漏洞。
    • 非常真实的 IMSoP。我质疑是否甚至包括以这种方式使 php 文件动态化的部分,因为我知道我不想占用空间来提及安全问题。
    • 如何确定图片的三个文件扩展名中的哪一个?
    • Pete,这是值得自己提出的问题,但既然你在这里问,请使用 exif_imagetype(),如 exif_imagetype(image.gif) == IMAGETYPE_GIF。文档位于php.net/manual/en/function.exif-imagetype.php
    【解决方案2】:

    您需要在提供图像的响应上设置特定标头以强制下载。

    Content-Disposition: attachment; filename=myawesomefilename.png
    

    否则它只会在浏览器中加载。

    所以发送该标头,然后只需链接到带有该标头的传递该图像的路径。

    【讨论】:

      【解决方案3】:

      发送一个标头告诉浏览器像这样下载它:

      header("Content-type: application/force-download")
      

      然后将文件本身的数据发送给他们,无需任何 HTML 或任何内容。

      这个例子截自PHP docs

      <?php
      $file = 'monkey.gif';
      
      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');
          header('Pragma: public');
          header('Content-Length: ' . filesize($file));
          ob_clean();
          flush();
          readfile($file);
          exit;
      }
      ?>
      

      【讨论】:

      • 没有名为application/force-download的媒体类型。
      【解决方案4】:

      如果“下载保存在服务器上的图片”是指“尝试让浏览器提供“另存为”对话框而不是只显示图像”,那么您可能需要考虑使用 Content-Disposition: attachment 标头提供图像的响应:

      Content-Disposition: attachment; filename="thefilename.jpg"
      

      您可以使用header function 在php 中设置标题。

      【讨论】:

        猜你喜欢
        • 2017-05-29
        • 2017-02-23
        • 2016-04-13
        • 2011-10-12
        • 1970-01-01
        • 1970-01-01
        • 2011-01-30
        • 1970-01-01
        相关资源
        最近更新 更多