自己幾年前的QQ圖片網(wǎng)站所有的內(nèi)容是直接復(fù)制上去了,這樣我們現(xiàn)在提供了下載功能,但是當(dāng)時并沒有下載地址了,這樣我們研究了一個可以自動當(dāng)用戶點擊下載時再把當(dāng)前文章中的圖片利用ZipArchive壓縮并實現(xiàn)下載,下面來看.
示例代碼如下:
- include("data/common.inc.php"); //加載數(shù)據(jù)庫
- $conn = mysql_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd) ;//or die(mysql_error());
- mysql_select_db($cfg_dbname,$conn);
- mysql_query("set Names '$cfg_db_language'");
- $id = intval(isset($_GET['id'])?$_GET['id']:0);
- if( $id )
- {
- $zipUrl = 'uploads/zip/'.$id.'.zip';
- if( file_exists($zipUrl) ) //判斷文件是否存在
- {
- echo '<script language="javascript">location.href="'.$zipUrl.'";</script>';
- exit;
- }
- else
- {
- $sql ="select url from ".$cfg_dbprefix."uploads where arcid=$id";
- $query = mysql_query( $sql );// or die(mysql_error());
- if( mysql_num_rows( $query ) )
- {
- $array = array();
- while( $rs = mysql_fetch_array( $query ) )
- {
- $array[] = substr($rs['url'],1,strlen($rs['url'])-1);
- }
- //print_r($array);
- create_zip($array, $zipUrl, true); //在這里創(chuàng)建壓縮文件
- echo '<script language="javascript">location.href="'.$zipUrl.'";</script>'; //創(chuàng)建好了再下載
- exit;
- }
- else
- {
- echo '參數(shù)錯誤';
- exit;
- }
- }
- }
- else
- {
- echo '參數(shù)錯誤';
- exit;
- }
- //查詢數(shù)據(jù)表
- /*創(chuàng)建一個zip文件*/
- function create_zip($files = array(),$destination = '',$overwrite = false) {
- if(file_exists($destination) && !$overwrite){ //檢測zip文件是否存在
- return false;
- }
- if(is_array($files)) { //檢測文件是否存在
- foreach($files as $file) { //循環(huán)通過每個文件
- if(file_exists($file)) { //確定這個文件存在
- $valid_files[] = $file;
- }
- }
- }
- if(count($valid_files)) {
- $zip = new ZipArchive(); //創(chuàng)建zip文件
- if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true){
- return false; //Vevb.com
- }
- foreach($valid_files as $file) { //添加文件
- $zip->addFile($file,$file);
- }
- $zip->close();
- return file_exists($destination);
- } else {
- return false;
- }
- }
前一段代碼是連接dedecms數(shù)據(jù)庫然后再進(jìn)行根據(jù)文件ID查找數(shù)據(jù)并進(jìn)行壓縮了,打包好之后利用js輸出就實現(xiàn)了下載,如果下次再下載這個文件就自動調(diào)用此文件而不再次打包查找數(shù)據(jù)庫了,這樣可以減少服務(wù)器負(fù)載哦.
新聞熱點
疑難解答
圖片精選