根據URL下載單個圖片與批量打包下載圖片(檔案同理)
阿新 • • 發佈:2018-12-12
根據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壓縮包的形式就行下載了,親測可用。