【问题标题】:How do I make a jpg image download like a pdf file does?如何像 pdf 文件一样下载 jpg 图像?
【发布时间】:2011-05-20 14:17:22
【问题描述】:

我请求以与 pdf 文件相同的方式下载 jpg 图像。

目前,如果我将 jpg 图像作为链接添加到网页,它将在另一个浏览器窗口中打开,而不是实际下载到用户计算机。但是,pdf文件会。

这是标准代码:

<a href="/images/my-image.jpg">download image</a>

我将不胜感激这方面的任何指导。

谢谢。

【问题讨论】:

  • 当文件被发送到浏览器时,您将需要修改您的网络服务器配置或编写一个修改标题的脚本。浏览器将始终尝试显示图像。
  • 您是否使用任何服务器端语言?如果是这样,我能想到的一种方法是使用 content-disposition 标头。 stackoverflow.com/questions/1012437/…

标签: jquery download


【解决方案1】:

最好的方法是设置您的网络服务器或服务器端脚本(php、asp.net 等)以使用 the Content-Disposition header 提供您的 jpg 文件:: p>

Content-Disposition: attachment; filename="my-image.jpg"

脚本:

服务器:

【讨论】:

    【解决方案2】:

    如果您的服务器上有 PHP,您可以这样做。

    <?php 
    // Force download of image file specified in URL query string and which 
    // is in the same directory as this script: 
    if(!empty($_GET['img'])) 
    { 
       $filename = basename($_GET['img']); // don't accept other directories 
       $size = @getimagesize($filename); 
       $fp = @fopen($filename, "rb"); 
       if ($size && $fp) 
       { 
          header("Content-type: {$size['mime']}"); 
          header("Content-Length: " . filesize($filename)); 
          header("Content-Disposition: attachment; filename=$filename"); 
          header('Content-Transfer-Encoding: binary'); 
          header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
          fpassthru($fp); 
          exit; 
       } 
    } 
    header("HTTP/1.0 404 Not Found"); 
    ?>
    

    HTML 看起来像这样

    <img src="/images/download.php?img=imagename.jpg" alt="test">
    

    【讨论】:

      【解决方案3】:

      您可以使用此处提到的建议: http://answers.yahoo.com/question/index?qid=20080417163416AAjlb7T

      看起来像这样:

      access_file.php:
      
      <?php
      
      $f= $_GET['file'];
      
      $filename = explode("/", $f);
      $filename = $filename[(count($filename)-1)];
      
      header('Content-Disposition: attachment; filename="'.$filename.'"');
      readfile($f);
      
      ?>
      

      如果您将 access_file.php 文件粘贴到您的图像文件夹中,那么您可以使用链接:

      <a href="/images/access_file.php?file=my-image.jpg" />
      

      【讨论】:

        【解决方案4】:

        如何从浏览器打开 PDF 内容类型取决于许多不同的设置。它可能会受到浏览器设置中与程序的内容类型关联的影响。它也可能受 PDF 阅读器本身的设置影响,例如,EditPreferences...Internet 标签下的 Adob​​e Reader PDF 文档是否应在浏览器或应用程序中直接打开的选项。

        【讨论】:

          【解决方案5】:

          在 HTML 5 中,我们有一个名为 download 的属性

          <a href="img/myimage.jpg" download="myimage.jpg"><img src="img/myimage.jpg" /></a>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-03-18
            • 1970-01-01
            • 1970-01-01
            • 2013-05-10
            • 2021-12-21
            • 2014-10-25
            • 2010-12-28
            • 1970-01-01
            相关资源
            最近更新 更多