PHP“另存为..“文件


PHP "Save as..." file

我想允许用户从服务器下载特定文件,并让他们选择文件名。

它是一个 JSON 文件。

我有以下有效的PHP脚本,但它会自动命名文件:

if (file_exists($myFile)){
    header ("Content-Type: application/download");
    header ("Content-Disposition: attachment; filename=$myFile");
    header("Content-Length: " . filesize("$myFile"));
    $fp = fopen("$myFile", "r");
    fpassthru($fp);
} else {
    echo "no file exists";
};  

浏览器会根据内容类型打开该另存为对话框。在浏览器中,用户可以指定哪种 MIME 类型应以哪种方式打开。

通常,您为 JSON 指定 MIME 类型 application/json - 请参阅 RFC 4627

您可以尝试将类型设置为 application/octet-stream

但正如我所写 - 这取决于用户设置。

在 Firefox 中可以这样修改:https://support.mozilla.org/en-US/kb/change-firefox-behavior-when-open-file

只需将header ("Content-Disposition: attachment; filename=$myFile");更改为header ("Content-Disposition: attachment; filename=$chosenFileName");其中$chosenFileName是用户提供的名称。

步骤 - 1 .首先,单击下载按钮打开带有输入文件名的表单(打开弹出窗口或其他页面(

步骤 - 2 现在给出文件名(我的意思是在文本框中输入名称并单击提交(;

步骤 - 3 提交时将请求作为帖子(方法 = 'POST'(发送到下载文件。 这看起来像 $_POST["文件名"];

步骤 - 4

if($_POST['filename']){
    $filename = $_POST['filename']; 
}
if (file_exists($myFile)){
    header ("Content-Type: application/download");
    header ("Content-Disposition: attachment; filename=$filename ");
    header("Content-Length: " . filesize("$filename "));
    $fp = fopen("$filename ", "r");
    fpassthru($fp);
} else {
    echo "no file exists";
};  

我希望这会对你有所帮助..!!