我想创建一个允许自定义下载组合的表单,就像jQuery UI download page上的表单一样。用户选择他/她需要的组件并组装自定义下载,(g)压缩并发送出去。这是如何运作的?我怎么写类似的东西?
可选:既然我想在Drupal 7网站上实现这一点,也欢迎提供有用模块的建议。
答案 0 :(得分:2)
简单实施:
<?php
// base directory containing files that we're adding
$dir = 'images/';
// name of our zip file. best to use a unique name here
$zipfile = "test.zip";
// get a directory listing, remove self/parent directories, and reindex array
$files = array_values(array_diff(scandir($dir), array('.', '..')));
// form has been submitted
if (isset($_POST['submit'])) {
// initialize the zip file
$output = new ZipArchive();
$output->open($zipfile, ZIPARCHIVE::CREATE);
// add files to archive
foreach ($_POST['file'] as $num=>$file) {
// make sure the files are valid
if (is_file($dir . $file) && is_readable($dir . $file)) {
// add it to our zip file
$output->addFile($dir . $file);
}
}
// write zip file to filesystem
$output->close();
// direct user's browser to the zip file
header("Location: " . $zipfile);
exit();
} else {
// display filenames with checkboxes
echo '<form method="POST">' . PHP_EOL;
for ($x=0; $x<count($files); $x++) {
echo ' <input type="checkbox" name="file[' . $x . ']" value="' . $files[$x] . '">' . $files[$x] . '<br>' . PHP_EOL;
}
echo ' <input type="submit" name="submit" value="Submit">' . PHP_EOL;
echo '</form>' . PHP_EOL;
}
?>
已知错误:不预先检查$zipfile
是否存在。如果是,则将附加到。
答案 1 :(得分:2)
jnpcl的答案有效。但是,如果要在不需要重定向的情况下下载文件,请执行以下操作:
// Once you created your zip file as say $zipFile, you can output it directly
// like the following
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename='.basename($zipFile));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($zipFile));
ob_clean();
flush();
readfile($zipFile);
答案 2 :(得分:1)