我需要实现一个代码,我可以让客户端在web服务器上下载一个或多个本地文件。
我有3个文件:file1.php, file1. js, file3.php与以下代码。
在<<p> strong> file1.php :<select name="file_list" class="myclass" id="f_list" style="height:25px; width: 280px">
<?php
foreach (new DirectoryIterator("$filesFolder") as $file)
{
if((htmlentities($file) !== ".") && (htmlentities($file) !== ".."))
{
echo "<option>" . htmlentities($file) . "</option>";
}
}
?>
</select>
<?php
echo "<input type='"button'" value='" Download '" onClick='"downloadFile()'"/>";
?>
在<<p> strong> file2.js function downloadFile()
{
$("#activity").html("<img src='"img.gif'" style='"left: 590px;top: 74px;margin: auto;position: absolute;width: 32px;height: 32px;'" />");
$("#content").load("file3.php",
{
filename: $("#f_list").val()
});
}
file3.php
if(isset($_POST["filename"]))
{
$filename = $_POST["filename"];
/* testing string */
echo $filesFolder.$filename;
if(file_exists($filesFolder.$filename))
{
ob_start();
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filesFolder.$filename));
readfile($filesFolder.$filename);
ob_end_flush();
exit;
}
}
我从readfile函数PHP手册中获取了最后这段PHP代码,因为这种行为正是我所需要的。但是当file3.php被执行时,文件的内容(二进制数据)被打印在屏幕上。
我想我错过了实现一些功能,但我不知道它可能是什么。我如何获得相同的结果readfile PHP手册页?
提前感谢您的帮助
File2:
您不能使用.load()
或类似的方法下载文件。
直接用window.location.href = "file3.php?filename="+$("#f_list").val();
File3:
在调用header()
s之前不能输出任何东西。注释掉第5行的echo
。
在文件2中,我们使用GET代替POST,将$_POST
替换为$_GET
。
不使用ajax请求页面可能也有帮助,只使用
window.location.href='/download/url';
如果所有标题都正确,它将打开一个下载对话框,而不离开当前页面。
一种方法是尝试在新选项卡/窗口中打开该文件:
function downloadFile()
{
window.open("file3.php?filename=" + encodeURIComponent($("#f_list").val()));
}
由于PHP页面的结果具有指示内容是下载而不是页面的标题,因此浏览器实际上不会导航,而是提供一个下载框。注意,此方法使用GET而不是POST,因此必须在file3.php中将$_POST
更改为$_GET
或$_REQUEST
。此外,确保在标题消失之前删除echo
,否则这将不起作用。