簡體   English   中英

zip中的php下載文件為空

[英]php downloaded files in zip are empty

目前,我正在嘗試將文件放在zip文件中並下載。 我使用以下代碼:

 # create new zip opbject
$zip = new ZipArchive();

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

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

    # download file
    $download_file = file_get_contents($file);

    #add it to the zip
    $zip->addFromString(basename($file),$download_file);

}

# close zip
$zip->close();

# send the file to the browser as a download
header('Content-disposition: attachment; filename=Resumes.zip');
header('Content-type: application/zip');
readfile($tmp_file);

通過以下方式將文件添加到陣列:

$weborder = $_POST['weborder'];
$printlocation = $_POST['print'];

$dir = "z:\Backup\\$printlocation\\$weborder.zip";

$zip = new ZipArchive; 
$files = array();

if ($zip->open($dir)) 
{
    for($i = 0; $i < $zip->numFiles; $i++) 
    {
        if ($zip->getNameIndex($i) != "order-info.txt" && $zip->getNameIndex($i) != "workrequest.xml" && $zip->getNameIndex($i) != "workrequest.pdf") 
        {
            $filename = $zip->getNameIndex($i);

            $files[$i] = $dir . "\\" . $filename;
        }
    }
}

這將下載zip以及zip中的文件。 我唯一的問題是文件為空。

此代碼有效,請確保您的文件存在或不存在。

$array = array("sites/README.txt","sites/chessboard.jpg"); //files to Add/Create in zip file

$zip = new ZipArchive(); // Load zip library 
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
{ 
 // Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($array as $key => $value)
{ 
    if(file_exists($value)){
        $zip->addFile($value); // Adding files into zip
    }else{echo $value ."&nbsp;&nbsp;file not exist<br/>";}
}
$zip->close();
if(file_exists($zip_name))
{
    echo "yes";die;
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}else{echo "zip not created";die; }

對於下載現有文件

 $zip_name = "YOUR_ZIP_FILE PATH";
    if(file_exists($zip_name))
    {
    // push to download the zip
    header('Content-type: application/zip');
    header('Content-Disposition: attachment; filename="'.$zip_name.'"');
    readfile($zip_name);
    // remove zip file is exists in temp path
    //unlink($zip_name);
    }else{
        echo "zip not created";exit; 
    }

代替

 $zip->addFromString(basename($file),$download_file);

嘗試

$zip->addFile($basename($file));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM