php 批量获取第三方图片,并压缩输出下载

4 篇文章 0 订阅
2 篇文章 0 订阅

解决方案

//需要下载的第三方图片链接数组
$img_list = [
    'http://img.mp.sohu.com/upload/20170710/18931bc763024d7cbd105e1b46804446.png',
    'http://img5.imgtn.bdimg.com/it/u=1289981276,3794620975&fm=15&gp=0.jpg'
];

$dfile = tempnam('/tmp', 'tmp'); //生成文件的临时位置和文件前缀,返回文件路径,包含文件名
$zip = new Imagedown(); //Imagedown这个类的代码会贴在后面
foreach ($images as $v){
    $zip->add_file(file_get_contents($v), basename($v));
}
$zip->output($dfile);
download($dfile);    //这个方法的代码也会贴在后面

Imagedown 类

//这个类的代码看不懂,还望各位路过的大神指点,感激不尽!
class Imagedown
{
    public $datasec = array();
    public $ctrl_dir = array();
    public $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
    public $old_offset = 0;
    public function unix2_dostime($unixtime = 0)
    {
        $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
        if ($timearray['year'] < 1980) {
            $timearray['year'] = 1980;
            $timearray['mon'] = 1;
            $timearray['mday'] = 1;
            $timearray['hours'] = 0;
            $timearray['minutes'] = 0;
            $timearray['seconds'] = 0;
        }
        return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) | ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
    }
    public function add_file($data, $name, $time = 0)
    {
        $name = str_replace('\\', '/', $name);
        $dtime = dechex($this->unix2_dostime($time));
        $hexdtime = '\x' . $dtime[6] . $dtime[7] . '\x' . $dtime[4] . $dtime[5] . '\x' . $dtime[2] . $dtime[3] . '\x' . $dtime[0] . $dtime[1];
        eval('$hexdtime = "' . $hexdtime . '";');
        $fr = "\x50\x4b\x03\x04";
        $fr .= "\x14\x00";
        $fr .= "\x00\x00";
        $fr .= "\x08\x00";
        $fr .= $hexdtime;
        $unc_len = strlen($data);
        $crc = crc32($data);
        $zdata = gzcompress($data);
        $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
        $c_len = strlen($zdata);
        $fr .= pack('V', $crc);
        $fr .= pack('V', $c_len);
        $fr .= pack('V', $unc_len);
        $fr .= pack('v', strlen($name));
        $fr .= pack('v', 0);
        $fr .= $name;
        $fr .= $zdata;
        $fr .= pack('V', $crc);
        $fr .= pack('V', $c_len);
        $fr .= pack('V', $unc_len);
        $this->datasec[] = $fr;
        $cdrec = "\x50\x4b\x01\x02";
        $cdrec .= "\x00\x00";
        $cdrec .= "\x14\x00";
        $cdrec .= "\x00\x00";
        $cdrec .= "\x08\x00";
        $cdrec .= $hexdtime;
        $cdrec .= pack('V', $crc);
        $cdrec .= pack('V', $c_len);
        $cdrec .= pack('V', $unc_len);
        $cdrec .= pack('v', strlen($name));
        $cdrec .= pack('v', 0);
        $cdrec .= pack('v', 0);
        $cdrec .= pack('v', 0);
        $cdrec .= pack('v', 0);
        $cdrec .= pack('V', 32);
        $cdrec .= pack('V', $this->old_offset);
        $this->old_offset += strlen($fr);
        $cdrec .= $name;
        $this->ctrl_dir[] = $cdrec;
    }
    public function add_path($path, $l = 0)
    {
        $d = @opendir($path);
        $l = $l > 0 ? $l : strlen($path) + 1;
        while ($v = @readdir($d)) {
            if ($v == '.' || $v == '..') {
                continue;
            }
            $v = $path . '/' . $v;
            if (is_dir($v)) {
                $this->add_path($v, $l);
            } else {
                $this->add_file(file_get_contents($v), substr($v, $l));
            }
        }
    }
    public function file()
    {
        $data = implode('', $this->datasec);
        $ctrldir = implode('', $this->ctrl_dir);
        return $data . $ctrldir . $this->eof_ctrl_dir . pack('v', sizeof($this->ctrl_dir)) . pack('v', sizeof($this->ctrl_dir)) . pack('V', strlen($ctrldir)) . pack('V', strlen($data)) . "\x00\x00";
    }
    public function add_files($files)
    {
        foreach ($files as $file) {
            if (is_file($file)) {
                $data = implode("", file($file));
                $this->add_file($data, $file);
            }
        }
    }
    public function output($file)
    {
        $fp = fopen($file, "w");
        fwrite($fp, $this->file());
        fclose($fp);
    }
}

download 方法

转自 https://blog.csdn.net/u013931660/article/details/52329764#commentBox 非常感谢!

public function download($file){  
   
        //First, see if the file exists  
        if (!is_file($file)) { die("<b>404 File not found!</b>"); }  
       
        //Gather relevent info about file  
        $len = filesize($file);  
        $filename = basename($file);  
        $file_extension = strtolower(substr(strrchr($filename,"."),1));  
       
        //This will set the Content-Type to the appropriate setting for the file  
        switch( $file_extension ) {  
          case "pdf": $ctype="application/pdf"; break;  
          case "txt": $ctype="application/txt"; break;  
          case "exe": $ctype="application/octet-stream"; break;  
          case "zip": $ctype="application/zip"; break;  
          case "doc": $ctype="application/msword"; break;  
          case "xls": $ctype="application/vnd.ms-excel"; break;  
          case "ppt": $ctype="application/vnd.ms-powerpoint"; break;  
          case "gif": $ctype="image/gif"; break;  
          case "png": $ctype="image/png"; break;  
          case "jpeg":  
          case "jpg": $ctype="image/jpg"; break;  
          case "mp3": $ctype="audio/mpeg"; break;  
          case "wav": $ctype="audio/x-wav"; break;  
          case "mpeg":  
          case "mpg":  
          case "mpe": $ctype="video/mpeg"; break;  
          case "mov": $ctype="video/quicktime"; break;  
          case "avi": $ctype="video/x-msvideo"; break;  
       
          //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)  
          case "php":  
          case "htm":  
          case "html":  
          //case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;  
       
          default: $ctype="application/force-download";  
        }  
       
        //Begin writing headers  
        header("Pragma: public");  
        header("Expires: 0");  
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");  
        header("Cache-Control: public");   
        header("Content-Description: File Transfer");  
           
        //Use the switch-generated Content-Type  
        header("Content-Type: $ctype");  
       
        //Force the download  
        $header="Content-Disposition: attachment; filename=".$filename.".zip;";  
        header($header);  
        header("Content-Transfer-Encoding: binary");  
        header("Content-Length: ".$len);  
        ob_clean();    
        flush();    //ob_clean和flush方法如果不加,可能会导致下载的压缩文件打不开,会比源文件大几kb
        @readfile($file);  
        exit;  
    }

------------------------------------------------------分割线------------------------------------------------------------------

思路

1,一开始返回结果是下图这样的,以为是header设置的问题

2,根据网上查到的header各种设置,结果返回还是上面那样,或者返回另一种乱码,应该就不是header的问题,实际下面的header就可以

3,打印 $dfile 变量,去服务器上把 /tmp/下对应生成的文件手动下载到本地解压,发现没问题(下载到本地的文件没有.zip后缀,要自己加上)

4,在地址栏请求方法可以正常下载,所以觉得是前端请求的问题(前端的请求是前端框架封装的),不知道是不是因为这个 原因 感谢!

5,最后重新封装了一下请求方法,搞定^_^

<li><a title="批量下载图片" rel="ids[]" href="javascript:downImg(this)"  warn="请选择数据" class="icon" ><span>批量下载图片</span></a>

<script>
	function downImg(that){
		var ids = new Array;
		$("input[name='ids[]']:checked").each(function(index,element){
			ids.push($(element).val());
		});
		// $a = $("<a id='sss' href=javascript:alert(\'哈哈哈\')></a>");
		$a = $("<a id='sss' href='__URL__/setAllImage?ids="+ids.join(',')+"'></a>");
		$('body').append($a);
		$('#sss')[0].click();
		$('#sss')[0].remove();
		// console.log($a.click())	;
	}
</script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值