根据url下载图片看起来很简单,做起来还是有点曲折的
首先,直接file_put_content()的话可以下载图片但不知道图片保存在什么位置,所以必须要调用浏览器下载,使用header头。
function download($url,$filename )
{
$title=substr($filename,strrpos($filename,'/')+1);
$file = fopen($url, "rb");
Header( "Content-type: application/octet-stream ");
Header( "Accept-Ranges: bytes ");
Header( "Content-Disposition: attachment; filename= $title"); //以附件方式下载并在浏览器显示
$contents = "";
while (!feof($file)) { //检查是否到文件尾
$contents .= fread($file, 8192);
}
echo $contents;
}
但是这个函数不能循环批处理下载,若要批量下载需要打包zip
function download_image($url, $fileName , $dirName, $fileType = array('jpg', 'gif', 'png'), $type = 1)
{
if ($url == '')
{
return false;
}
// 获取文件原文件名
$defaultFileName = $fileName;
// 获取文件类型
$suffix = substr(strrchr($url, '.'), 1);
if (!in_array($suffix, $fileType))
{
return false;
}
// 设置保存后的文件名
$fileName = $fileName == '' ? time() . rand(0, 9) . '.' . $suffix : $defaultFileName;
// 获取远程文件资源
if ($type)
{
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file = curl_exec($ch);
curl_close($ch);
}
else
{
ob_start();
readfile($url);
$file = ob_get_contents();
ob_end_clean();
}
if (!file_exists($dirName))
{
mkdir($dirName, 0777, true);
}
// 保存文件
$res = fopen($dirName . '/' . $fileName, 'a');
fwrite($res, $file);
fclose($res);
return array(
'fileName' => $fileName,
'saveDir' => $dirName
);
}
$zip = new ZipArchive();
$zipname = "./qrcode.zip";
$dir = dirname(__FILE__).'/image' ;
if ($zip->open($zipname, ZIPARCHIVE::CREATE)!==TRUE) {
exit('不存在');
}
foreach ($images as $url){
$filename =substr($url,strrpos($url,'/')+1);
download_image($url,$filename,$dir);
$zip->addFile( $dir.'/'.$filename,$filename);
}
$zip->close();
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.basename($zipname)); //文件名
header("Content-Type: application/zip"); //zip格式的
header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
header('Content-Length: '. filesize($zipname));
@readfile($zipname);
然后浏览器就会以zip压缩包的形式就行下载了,亲测可用。