PHP“;另存为……”;文件

PHP“;另存为……”;文件,php,Php,我希望允许用户从服务器下载特定文件,并让他们选择文件名 它是一个JSON文件 我使用了以下PHP脚本,但它会自动命名文件: if (file_exists($myFile)){ header ("Content-Type: application/download"); header ("Content-Disposition: attachment; filename=$myFile"); header("Content-Length: " . filesize("$m

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

它是一个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";
};  

只需更改
标题(“内容处置:附件;文件名=$myFile”)将成为
标题(“内容处置:附件;文件名=$chosenFileName”)其中$chosenFileName是用户提供的名称。

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

顺便说一句,通常为json指定mime类型
application/json
——请参阅RFC4627

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

但正如我所写的,这取决于用户设置

在firefox中,可以通过以下方式进行修改:
第1步。首先,单击下载按钮打开带有输入文件名的表单(打开弹出窗口或其他页面)

第2步现在给出文件名(我的意思是在文本框中输入名称并单击submit)

步骤3:将发送请求作为post(方法='post')提交到下载文件。 这看起来像$_POST['filename']

步骤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";
};  

我希望这对你有帮助

这完全取决于浏览器为用户提供名称选择或使用“默认”名称保存。您好,这是一个想法,但是当用户单击运行此脚本的按钮时,$chosenFileName应该在对话框中提供,这是一个相当尴尬的解决方案。浏览器有自己的另存为对话框,此解决方案会创建另一个另存为对话框。这意味着,将浏览器设置为自动下载文件的用户(即不希望看到“另存为”对话框的用户)将看到该对话框的版本,而将浏览器设置为显示“另存为”对话框的用户将看到两个“另存为”对话框。