我有一个表单,用户可以上传100 MB的文件,导致上传延迟,因此我决定首先在表单提交上压缩图像,然后将其上传到服务器上,然后在服务器上提取。因此加载过程减少了,因此我使用了一个脚本,如下所示:
<?php
$zip = new ZipArchive();
$filename = "newzip.zip";
if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString("myfile.jpeg",
"This is the first file in our ZIP, added as
firstfile.txt.\n");
echo "numfiles: " . $zip->numFiles . "\n";
$zip->close();
$zip1 = zip_open("newzip.zip");
if ($zip1) {
while ($zip_entry = zip_read($zip1)) {
$fp = fopen(zip_entry_name($zip_entry), "w");
if (zip_entry_open($zip1, $zip_entry, "r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
fwrite($fp,"$buf");
zip_entry_close($zip_entry);
fclose($fp);
}
}
zip_close($zip1);
unlink("newzip.zip");
}
?>
现在从上面的代码中我得到了提取的图像,但是在提取之后,图像的大小减少到61个字节并且已经损坏,即无法查看。
此代码有什么问题请指导我
答案 0 :(得分:2)
我认为你在这里混淆了客户端和服务器端。您根本无法创建ZIP客户端,因为PHP脚本在服务器端执行。因此,您必须在提交文件之前指示您的用户压缩文件,或使用ie。一个Java applet,用于在上传之前为它们压缩文件。
答案 1 :(得分:0)
$zip->addFromString("myfile.jpeg",
"This is the first file in our ZIP, added as
firstfile.txt.\n");
也许你想要的是:
$zip->addFromString("firstfile.txt",
"This is the first file in our ZIP, added as
firstfile.txt.\n");
您获得的61字节文件是您首先添加的文件!
echo strlen("This is the first file in our ZIP, added as
firstfile.txt.\n");
给出61
。
答案 2 :(得分:0)
请检查以下脚本,该脚本仅从zip文件中提取图像并排除所有其他文件。就像你可以添加所有其他mime类型一样。
<?php
$dir = __DIR__;
$extractedFilesDir = $dir . "/images";
$zipFile = $dir . "/image.zip");
$zipFileName = basename($zipFile, '.zip');
$fieDir = $extractedFilesDir . '/' . $zipFileName;
if (class_exists('ZipArchive')) {
$zip = new ZipArchive;
$result = $zip->open($zipFile, ZipArchive::CHECKCONS);
if ($result === TRUE) {
$noImageFound = true;
for ($i = 0; $i < $zip->numFiles; $i++) {
$onlyFileName = $zip->getNameIndex($i);
$fileType = mime_content_type('zip://' . $zipFile . '#' . $onlyFileName);
$fileType = strtolower($fileType);
if (($fileType == 'image/png' || $fileType == 'image/jpeg' || $fileType == 'image/gif' || $fileType == 'image/svg') && (preg_match('#\.(SVG|svg|jpg|jpeg|JPEG|JPG|gif|GIF|png|PNG)$#i', $onlyFileName))) {
//copy('zip://' . $zipFile . '#' . $onlyFileName, $fieDir . '/' . $onlyFileName);
$zip->extractTo($extractedFilesDir, array($zip->getNameIndex($i)));
$noImageFound = false;
echo 'extracted the image ' . $onlyFileName . ' from ' . $zipFile . ' to ' . $fieDir . '<br />';
}
}
if ($noImageFound) {
echo 'There is no images in zip file ' . $zipFile . '<br />';
}
} else {
switch ($result) {
case ZipArchive::ER_NOZIP:
echo 'Not a zip archive ' . basename($zipFile);
case ZipArchive::ER_INCONS:
echo 'Consistency check failed ' . basename($zipFile);
case ZipArchive::ER_CRC:
echo 'checksum failed ' . basename($zipFile);
default:
echo 'Error occured while extracting file ' . basename($zipFile);
}
}
$zip->close();
}