【问题标题】:Download a file with php and polymer下载带有 php 和聚合物的文件
【发布时间】:2015-12-23 20:27:14
【问题描述】:

我遇到了一些麻烦。我在网上找到了一些有用的脚本,并一直在修改它们以满足我的需要。但是,我似乎无法下载文件。它会回复文件的内容,但不会下载它。我在客户端使用 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);
}

对此的任何帮助将不胜感激。

【问题讨论】:

  • 你需要写读。

标签: php polymer-1.0 webclient


【解决方案1】:

首先你需要文件句柄

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

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

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

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

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

fclose($writeHandle);

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

【讨论】:

  • 这很好用。我测试了这将有多种类型。但是,我希望在浏览器中进行某种下载,以便我可以看到它正在发生,而不是在没有视觉更新的幕后进行。
  • 我能够通过浏览器下载它,方法是打开我的 php 代码的 url,而不使用 Iron-ajax。例如:window.location.href = "path/to/php/function";
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-16
相关资源
最近更新 更多