下载zip文件中的照片

时间:2017-03-28 13:19:10

标签: php mysql html5

大家好,非常感谢你们给予的任何帮助。这里的代码是使用表单将img上传到mysql数据库,这是数据库。

数据库

CREATE TABLE `user_pic` (
    `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
    `img` LONGBLOB NOT NULL,
    `img_name` VARCHAR(200) NOT NULL,
    `upload_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `user_id` INT(11) NULL DEFAULT NULL,
    PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB

这里我将所有照片加载到变量

load_img.php

$couple_login_id = $_SESSION['users']['id'];
$statement = $conexion->prepare("SELECT * FROM user_pic WHERE user_id = $couple_login_id");
$statement->execute();
$fotos = $statement->fetchAll();

在这里我循环所有图像并在html上显示图像

gallery.php

    <?php foreach($fotos as $foto):?>
      <div class="col-xs-12 col-sm-4 col-md-3 item-photo">
        <div class="photo">
          <?php echo '<img class="img-responsive" src="data:image/jpeg;base64,'.base64_encode( $foto['img'] ).'"/>';?>
          <?php echo '<a class="search zoom fancybox" href="data:image/jpeg;base64,'.base64_encode( $foto['img'] ).'"><span class="icon-search"></span></a>';?>
          <?php if($_SESSION['users']["user_rol"] == 1):?>
            <a class="star" href="#"><span class="icon-star"></span></a>
          <?php endif;?>
          <a class="download" href="#"><span class="icon-download"></span></a>
        </div>
      </div>
    <?php endforeach;?>

这个代码可以下载zip文件中的所有照片。 的 download_zip.php

  $zip = new ZipArchive();

  # create a temp file & open it
  $tmp_file = tempnam('.','');
  $zip->open($tmp_file, ZipArchive::CREATE);

  # loop through each file
  foreach($fotos as $file){

      # download file
      $download_file = file_get_contents($file['img']);

      #add it to the zip
      $zip->addFile($download_file);

  }

  # close zip
  $zip->close();

      # send the file to the browser as a download
     header("Content-type: application/zip"); 
     header("Content-Disposition: attachment; filename=wedding_photos.zip");
     header("Content-length: " . filesize('wedding_photos.zip'));
     header("Pragma: no-cache"); 
     header("Expires: 0"); 
     readfile('wedding_photos.zip');

问题是,当我创建zip文件并下载它时,我可以打开它,因为sed该文件具有未知格式或已损坏。如果代码有问题,或者因为照片存储在数据库中的方式,我不会这样做。感谢您给我的帮助。 :d

2 个答案:

答案 0 :(得分:0)

设置路径

  

$ zip-&GT; addFile( “$ FILE_PATH”,$ download_file);

添加描述zip文件大小的Content-length标头,以字节为单位。

header("Content-type: application/zip"); 
header("Content-Disposition: attachment; filename=wedding_photos.zip");
header("Content-length: " . filesize('wedding_photos.zip'));
header("Pragma: no-cache"); 
header("Expires: 0"); 
readfile('wedding_photos.zip');

答案 1 :(得分:0)

当您使用二进制数据而不是文件时,应使用addFromString方法。所以你可以改变代码:

$zip = new ZipArchive();

// create a temp file & open it
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);

// loop through each file
foreach ($fotos as $file) {
    //add it to the zip
    $zip->addFromString($file['img_name'], $file['img']);
}

// close zip
$zip->close();