【问题标题】:Download image code in php用php下载图片代码
【发布时间】:2013-02-07 06:47:05
【问题描述】:

我是 php 的新手,希望编写一个下载代码,允许用户下载图像。这意味着我已经给出了一个下载链接 onclick 位于服务器上的图像应该开始下载。我尝试了各种选项,如 fopen、curl 等,但无济于事。在使用 curl 时,图像会下载,但不会在下载位置打开。它给出错误消息“无法读取文件头!未知文件格式。”请帮助这是我使用的 curl 代码:

function DownloadImageFromUrl($imagepath)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch,CURLOPT_URL, $imagepath);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
curl_close($ch);
return $result;
}

$imagecontent =DownloadImageFromUrl("http://www.xyz.com/back_img.png");
$savefile = fopen('myimage.png', 'w');
fwrite($savefile, $imagecontent);
fclose($savefile);

【问题讨论】:

    标签: php image curl


    【解决方案1】:

    您应该为此使用 http 标头

    header('Content-Type: "'.$mime.'"');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header("Content-Transfer-Encoding: binary");
    header('Expires: 0');
    header('Pragma: no-cache');
    header("Content-Length: ".strlen($data));
    exit($data);
    

    mime - 图像的 MIME 类型

    filename - 下载文件的名称

    数据 - 文件。您可以使用以下方法从其他服务器获取图像:

    $data = file_get_contents('http://www.xyz.com/back_img.png')
    

    【讨论】:

      【解决方案2】:

      试试这个

      $imagecontent =DownloadImageFromUrl("http://www.xyz.com/back_img.png");
      $savefile = fopen('myimage.png', 'r');
      fread($savefile, $imagecontent);
      fclose($savefile);
      

      【讨论】:

        【解决方案3】:
        function downloadFile ($url, $path) {
        
          $newfname = $path;
          $file = fopen ($url, "rb");
          if ($file) {
            $newf = fopen ($newfname, "wb");
        
            if ($newf)
            while(!feof($file)) {
              fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
            }
          }
        
          if ($file) {
            fclose($file);
          }
        
          if ($newf) {
            fclose($newf);
          }
         }
        
        downloadFile ("http://www.site.com/image.jpg", "images/name.jpg");
        

        【讨论】:

          【解决方案4】:

          您需要添加header() 方法使其作为可下载项目打开。

          header("Content-Type: application/force-download"); 
          header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" ); 
          

          在哪里

          $fullPath是图片路径。

          更多规格请参考-header in php

          【讨论】:

            猜你喜欢
            • 2011-08-12
            • 2010-11-23
            • 1970-01-01
            • 1970-01-01
            • 2012-04-05
            • 2016-05-03
            • 1970-01-01
            • 1970-01-01
            • 2023-03-08
            相关资源
            最近更新 更多