我使用html& amp;创建了多个文件上传器PHP。上传器功能正常但我尝试创建ZIP以便将上传的文件添加到ZIP文件中。在这种情况下,无法创建zip并将上传的文件添加到zip中。我不知道为什么它不起作用。
请检查下面的脚本,如果我提前感谢错过任何事情,请告诉我们:
Html脚本:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File Upload with Progress Bar</title>
<script type="text/javascript">
// select file function only for styling up input[type="file"]
function select_file(){
document.getElementById('image').click();
return false;
}
</script>
</head>
<body>
<div class="container">
<!--status message will appear here-->
<div class="status"></div>
<!--image upload form-->
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a file</a>
<input id="image" type="file" multiple="multiple" name="files[]" >
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
</div>
</body>
</html>
Php脚本:
header('Content-type: application/json');
$path = 'uploads/'; // upload directory
if (!file_exists('uploads')) {
mkdir('uploads', 0777, true);
}
$max_file_size = 1024*10000; // 1024 byte= 1kb 1024*100 byte=100kb
$count = 0;
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
$zip_path = 'download.zip';
$zip = new ZipArchive();
if ($zip->open($zip_path, ZIPARCHIVE::OVERWRITE) !== TRUE) {
die ("An error occurred creating your ZIP file.");
}
foreach ($_FILES['files']['name'] as $f => $name) {
$filename = $_FILES['files']['name'][$f];
$filecontent = file_get_contents($_FILES["files"]["tmp_name"][$f]);
$filetype = $_FILES['files']['type'][$f];
$filesize = $_FILES['files']['size'][$f];
$fileext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);;
$zip->addFromString($filename, $filecontent);
//$zip->addFile('file_on_server.ext', 'second_file_name_within_archive.ext');
if ($_FILES['files']['error'][$f] == 4) {
$status[] ='Upload Fail: Unknown error occurred!';
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$status[] = "$name is too large!.";
continue; // Skip large files
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name)){
$count++; // Number of successfully uploaded file
$status[] = 'Image successfully uploaded!';
}
else {
$status[] = 'Upload Fail: Unknown error occurred!';
}
}
}
}
$zip->close();
}
else {
$status[] = 'Bad request!';
}
echo json_encode(array('status' => $status));
答案 0 :(得分:0)
它可能无法正常工作。您的目录中不存在download.zip文件。 您能否请创建download.zip文件或替换以下代码,然后再试一次:
if ($zip->open($zip_path,ZIPARCHIVE::OVERWRITE) !== TRUE)
{
die ("An error occurred creating your ZIP file.");
}
使用
if ($zip->open($zip_path,ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE)
{
die ("An error occurred creating your ZIP file.");
}