【问题标题】:Yii2 sendfile responseYii2 发送文件响应
【发布时间】:2015-07-24 09:54:14
【问题描述】:

我是 Yii2 的新手,如果有人能帮助我解决问题,我将不胜感激。我想制作一个下载链接并使用

Yii::$app->response->sendFile($path, $name, ['inline' => false])->send();

在下载功能中,但它只是读取文件的内容并直接显示在页面中。我想要做的是当用户单击下载链接时,会弹出下载对话框或自动下载文件,而不是显示内容。谁能帮帮我?

【问题讨论】:

  • 这可能根本与 Yii2 无关,而是因为您的浏览器从未收到 mime 类型或无法识别它。您要发送什么类型的内容?也许使用 firebug 或浏览器的调试工具来检查是否收到了 mime 类型

标签: response yii2 sendfile


【解决方案1】:

我遇到了完全相同的问题。事实证明,我的下载操作链接放置在 Pjax::begin() Pjax::end() 方法中,因此文件的内容被视为页面的更新。

我的解决方案:将data-pjax="0"属性添加到下载链接。

【讨论】:

  • 干得好。我不知道 Pjax 会干扰下载。
  • 应该被选为真正的答案。非常感谢!
【解决方案2】:

你可以做的是使用php头函数:

public function actionDownload() {
    $file = $_GET["file"];
    $name = str_replace('files/prices/', '', $file);

    header("Content-Disposition: attachment; filename=\"" . urlencode($name) . "\"");
    header("Content-Type: application/pdf");
    header("Content-Description: File Transfer");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($file));

    ob_clean();
    flush();

    readfile($file);
}

然后像这样调用链接,带有时间戳: http://page.com/download?file=files/prices/sillas.pdf&ts=1490725032

【讨论】:

    【解决方案3】:

    而不是:

     sendFile();
    

    试试:

    xSendFile()
    

    【讨论】:

      【解决方案4】:
      $mimetype='zip'; $mimetype='csv';
      Yii::$app->response->sendFile($path.$name, $name, ['mimeType'=>$mimetype, 'inline'=>false]);    
      return true;
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 2014-05-19
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 2021-01-17
      • 2014-05-26
      • 2017-12-05
      相关资源
      最近更新 更多