我正在创建一个 wordpress 页面,允许用户在 5 秒后下载一个 zip 文件。在其中,我正在调用第二个页面并传递 POST 参数(zip id::以获取 zip 路径)。该页面被调用但始终作为弹出窗口。我正在寻找一个干净的下载选项,无需打开标签页或新窗口即可开始下载。也绕过弹出窗口 - 拦截器。
我试过两种方法
A)方法一(Jquery Post)
$.post(
"<?php echo get_permalink(get_page_by_title('Download Page')); ?>",
{attachment_path: "<?php echo $attachment[0]->ID ; ?>"
}
B) 方法二(提交表单)
$( '<form action="" method="post" target="_parent" class="hide">
<input type="hidden" name="attachment_path" value="<?php echo $attachment[0]->ID ; ?>" />
<input type="submit" name="submit" value="submit" id="target-counter-button"/>
</form>'
).submit();
编辑
1) 寻找实现逻辑的POST方法
2) 由于服务器限制,直接访问*.php 文件和*.zip 文件已被阻止
3) 父级下载页面应在此过程中保持打开状态
就此问题寻求专家建议。
谢谢
最佳答案
您可以通过重定向到 php 脚本的路径来实现此目的,php 脚本将输出具有正确 HTTP header 的所需文件。
Javascript 部分:
5 秒后使用 zip id 重定向到“zipfetcher”脚本
<script>
function download(id) {
setTimeout(function () {
document.location = "zipfetcher.php?fileid="+id; // The path of the file to download
}, 5000); // Wait Time in milli seconds
}
</script>
<a href="#" onclick="download('123');return false;">Click to download in 5 sec!</a> // Call of the download function when clicked
PHP 部分:(又名 zipfetcher.php)
根据zipid找到zip路径然后用readfile输出使用正确的标题到浏览器
// Fetch the file path according to $_GET['fileid'] who's been sent by the download javascript function etc.
// ....
header('Content-Description: File Transfer');
header('Content-Type: application/zip, application/octet-stream'); // Puting the right content type in this case application/zip, application/octet-stream
header('Content-Disposition: attachment; filename='.basename($filepath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit;
关于javascript - 下载文件时禁止打开弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26063109/