下载包含 php 和聚合物的文件

Download a file with php and polymer

我在这方面遇到了一些麻烦。我在网上找到了一些有用的脚本,并一直在根据我的需要修改它们。但是,我似乎无法下载文件。它会用文件的内容进行响应,但不会下载它。我在客户端使用 Polymer 1.0+,在服务器端使用 PHP。下载文件的客户端代码如下:

   <!--THIS IS THE HTML SIDE-->
   <iron-ajax   
        id="ajaxDownloadItem"
        url="../../../dropFilesBackend/index.php/main/DownloadItem"
        method="GET"
        handle-as="document"
        last-response="{{downloadResponse}}"
        on-response="ajaxDownloadItemResponse">
    </iron-ajax>

//THIS IS THE JAVASCRIPT THAT WILL CALL THE "iron-ajax" ELEMENT
downloadItem:function(e){ 
    this.$.ajaxDownloadItem.params = {"FILENAME":this.selectedItem.FILENAME,
                                      "PATH":this.folder};
    this.$.ajaxDownloadItem.generateRequest();
},

服务器端代码如下(url不同,因为我做了一些url修改以获得正确的脚本):

function actionDownloadItem(){
    valRequestMethodGet();
    $username = $_SESSION['USERNAME'];
    if(validateLoggedIn($username)){
        $itemName = arrayGet($_GET,"FILENAME");
        $path = arrayGet($_GET,"PATH");
        $username = $_SESSION['USERNAME'];

        $downloadItem = CoreFilePath();
        $downloadItem .= "/".$_SESSION['USERNAME']."".$path."".$itemName;

        DownloadFile($downloadItem);
    }
    else {
        echo "Not Logged In.";
    }
}

function DownloadFile($filePath) {
    //ignore_user_abort(true);
    set_time_limit(0); // disable the time limit for this script
    //touch($filePath);
    //chmod($filePath, 0775);

    if ($fd = fopen($filePath, "r")) {
        $fsize = filesize($filePath);//this returns 12
        $path_parts = pathinfo($filePath);//basename = textfile.txt
        $ext = strtolower($path_parts["extension"]);//this returns txt
        $header = headerMimeType($ext); //this returns text/plain
        header('Content-disposition: attachment; filename="'.$path_parts["basename"].'"'); // use 'attachment' to force a file download
        header("Content-type: $header");
        header("Content-length: $fsize");
        header("Cache-control: private"); //use this to open files directly
        while(!feof($fd)) {
            $buffer = fread($fd, 2048);
            echo $buffer;
        }
    }
    fclose ($fd);
}

如有任何帮助,我们将不胜感激。

首先你需要文件句柄

$pathToSave = '/home/something/something.txt';

$writeHandle = fopen($pathToSave, 'wb');

然后,当您正在阅读下载时,写入文件而不是回显

fwrite($writeHandle, fread($fd, 2048));

最后,写入文件完成后关闭句柄

fclose($writeHandle);

我忽略了错误检查,你应该自己实现。