使用 PHP 标头将文件保存在本地 PC 中


Save file in local pc using PHP headers

我正在开发一个SVG编辑器。我必须将svg图片保存在本地磁盘上。如您所知,出于安全原因,不可能直接使用javascript进行操作。所以我决定通过服务器端帮助来解决这个问题。我在一个名为"savefile.php"的文件中编写了以下PHP例程:

    <?php
$mime = array('xls' => 'application/vnd.ms-excel', 'xml' => 'application/xml', 'html' => 'text/html', 'cvs' => 'text/plain', 'svg' => 'text/plain', 'txt' => 'text/plain', 'json' => 'text/plain',  'array' => 'text/plain');
if (isset($_POST['format']) && isset($_POST['filename']) && isset($_POST['content'])) {
    $filename = $_POST['filename'];
    $format = $_POST['format'];
    $content = $_POST['content'];
    $fullName = $filename . '.' . $format;
    header('Pragma: public');
    header("Content-Description: File Transfer");
    header("Content-Transfer-Encoding: binary");
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header("Cache-Control: public");
    header('Content-Type: ' . $mime[$format]);
    header('Content-Disposition: attachment; filename="' . basename($fullName) . '"');
    echo $content;
}
?>

在服务器端,我调用PHP过程,使用以下代码:

        var obj = {
            format: 'svg',
            filename: 'myfilename',
            content: glb.Draw_active().GetDisegno().svg()
            };
        $.post("php/savefile.php",obj,function(data,status,xhr){console.log('Executed');});

当软件执行上述代码时,浏览器应打开保存文件窗口并等待用户的确认.....但什么也没发生。我确定 PHP 例程被执行,它也执行回调例程,但没有别的。出了点问题,我的怀疑是在javascript客户端代码上,但我找不到任何文档。可能有人有这个程序的经验吗?

多谢。

感谢@Quentin的帮助,我解决了这个问题。上面的PHP代码正在工作,我不得不更改Javascript部分。这里是工作代码:

保存文件例程:

/*
    @datatype       : 'svg', 'xml', 'txt', 'xls', 'csv', 'html', etc see the list in PHP file
    @filename       : filename without extension
    @exportServer   : name of the PHP file on the server
    @content        : content of the file to save
*/
var saveFile = function(datatype, filename, exportServer,content){
    var HInput = function(value, name, form) {
        var I = document.createElement('input');
        I.name = name;
        I.value = value;
        I.type = 'hidden';
        form.appendChild(I);
        },
    HTextArea = function(value, name, form) {
         var tA = document.createElement('textarea');
         tA.name = name;
         tA.value = value;
         form.appendChild(tA);
         };
    var form = document.createElement('form');
    HInput(filename, 'filename', form);
    HInput(format, 'format', form);
    HTextArea(content, 'content', form);
    form.action = exportServer;
    form.method = 'post';
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
    }

....对于我的需要,我以这种方式调用它:

saveFile('svg','myfilename',"php/savefile.php",data);

仅此而已。。;)