当前位置:首页 > CMS教程 > DeDecms > 列表

dedecms实现自动打包文章中图片并下载

发布:smiling 来源: PHP粉丝网  添加日期:2014-10-17 16:55:51 浏览: 评论:0 

自己几年前的QQ图片网站所有的内容是直接复制上去了,这样我们现在提供了下载功能,但是当时并没有下载地址了,这样我们研究了一个可以自动当用户点击下载时再把当前文章中的图片利用ZipArchive压缩并实现下载,下面来看示例代码,代码如下:

  1. include("data/common.inc.php"); //加载数据库 
  2. $conn = mysql_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd) ;//or die(mysql_error()); 
  3. mysql_select_db($cfg_dbname,$conn); 
  4. mysql_query("set Names '$cfg_db_language'"); 
  5. $id = intval(isset($_GET['id'])?$_GET['id']:0); 
  6. if( $id ) 
  7. { 
  8.  $zipUrl = 'uploads/zip/'.$id.'.zip'; 
  9.  if( file_exists($zipUrl) ) //判断文件是否存在 
  10.  { 
  11.   echo '<script language="javascript">location.href="'.$zipUrl.'";</script>';   
  12.   exit; 
  13.  } 
  14.  else 
  15.  { 
  16.   $sql ="select url from ".$cfg_dbprefix."uploads where arcid=$id"; 
  17.   $query = mysql_query( $sql );// or die(mysql_error()); 
  18.   if( mysql_num_rows( $query ) ) 
  19.   { 
  20.     
  21.    $array = array(); 
  22.    while( $rs = mysql_fetch_array( $query ) ) 
  23.    { 
  24.     $array[] = substr($rs['url'],1,strlen($rs['url'])-1); 
  25.    } 
  26.    //print_r($array); 
  27.    create_zip($array, $zipUrl, true); //在这里创建压缩文件 
  28.    echo '<script language="javascript">location.href="'.$zipUrl.'";</script>'; //创建好了再下载  
  29.    exit; 
  30.   } 
  31.   else 
  32.   { 
  33.    echo '参数错误'; 
  34.    exit; 
  35.   } 
  36.  } 
  37. } 
  38. else 
  39. { 
  40.  echo '参数错误'; 
  41.  exit; 
  42. } 
  43. //查询数据表 
  44.  
  45.  
  46.  
  47. /*创建一个zip文件*/ 
  48. function create_zip($files = array(),$destination = '',$overwrite = false) { 
  49.  if(file_exists($destination) && !$overwrite){ //检测zip文件是否存在 
  50.   return false; 
  51.  } 
  52.  if(is_array($files)) { //检测文件是否存在 
  53.   foreach($files as $file) { //循环通过每个文件 
  54.    if(file_exists($file)) { //确定这个文件存在 
  55.     $valid_files[] = $file; 
  56.    } 
  57.   } 
  58.  } 
  59.  if(count($valid_files)) { 
  60.   $zip = new ZipArchive(); //创建zip文件 
  61.   if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true){ 
  62.    return false; 
  63.   } 
  64.   foreach($valid_files as $file) { //添加文件 
  65.    $zip->addFile($file,$file); 
  66.   }  //phpfensi.com 
  67.   $zip->close(); 
  68.   return file_exists($destination); 
  69.  } else {  //phpfensi.com 
  70.   return false; 
  71.  } 
  72. } 

前一段代码是连接dedecms数据库然后再进行根据文件ID查找数据并进行压缩了,打包好之后利用js输出就实现了下载,如果下次再下载这个文件就自动调用此文件而不再次打包查找数据库了,这样可以减少服务器负载.

Tags: dedecms图片下载 dedecms文章图片

分享到: