【问题标题】:Serving a file as download doesn't work? Seems a header issue?将文件作为下载服务不起作用?似乎是标题问题?
【发布时间】:2016-08-26 04:08:56
【问题描述】:

我有一个脚本,它生成一个通过 ajax 下载的文件。我需要控制这个请求,因为不是每个人都应该能够下载文件。流程如下:

  1. 监听点击事件,向服务器发送带有数据的ajax请求
  2. 处理请求,如果一切正常,将生成一个临时文件,第一行作为文件名,进一步的内容是要下载的文件的内容
  3. 将新生成文件的 URL 发送回 ajax 函数,并使用该端点填充隐藏的 iframe 的 src 属性。
  4. 调用端点时,控制器方法会检查文件是否存在,打开它并使用array_shift 将第一行放入$filename 变量中,并将其余内容放入$content 变量中,
  5. 设置下载标头并回显$content 变量。

不知何故,这并没有按预期工作。这不是因为 iframe,因为当我在浏览器中访问 URL 时,Chrome 告诉我出现 ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION 错误。我正在使用 Laravel,但我没有看到我在哪里设置了错误的标题?

目前的下载脚本:

public function download($fileId)
{
    $file = $this->tempFilesPath . $fileId;

    if (file_exists($file)) {
        $data         = explode("\n", file_get_contents($file));
        //@unlink($file);

        $fileName  = array_shift($data);
        $content   = implode("\n", $data);

        header('Content-Type: application/force-download');
        header('Content-Disposition: attachment; filename=' . $fileName);

        echo $content;
        exit;
    }
}

转储$fileName$content 的值会显示预期值。

建议?谢谢。

【问题讨论】:

  • 是的,标题似乎有错误。没有完成你的逻辑,但这里有一个链接可以帮助你stackoverflow.com/questions/386845/… 同样在同一点上,最好将 document.location 设置为链接,文件将被下载而不是重定向到下载链接。
  • 感谢您的回复,太糟糕了,将内容类型更改为 application/octet-stream 没有帮助。

标签: php


【解决方案1】:

经过一些额外的挖掘I found a post that writes about this specific error。这是因为我正在用日期格式化文件名,其中包含一个让 Chrome 感到不安的逗号。更改了文件名约定,现在可以使用。如果其他人以后可能会遇到这种行为,我会将问题留在网上。

对于未来的解决方案寻求者:

我首先将文件命名为$filename = 'download_' . date('d-m-Y, H:i:s') . '.ext',但日期格式中的逗号是导致问题的原因。把它放在一边,你应该更进一步解决你的问题。

【讨论】:

  • 在您的答案中发布相关代码更改,以防博文下线。这将对其他人有所帮助。
  • 我提到了修复。但为了进一步澄清,我将添加一些说明性代码。
  • 谢谢。这可能会对将来的某人有所帮助。
  • 该链接中的解决方案 #1 对我有用。在文件名周围添加引号,如下所示:header('Content-Disposition: attachment; filename="'.$file_name.'"');
【解决方案2】:

你可以像这样修改你的下载方法:

public function download($fileId) {
    $file     = $this->tempFilesPath . $fileId;

    if (file_exists($file)) {
        //$data           = explode("\n", file_get_contents($file));
        //@unlink($file);
        //$content    = implode("\n", $data);   
        //$fileName   = array_shift($data);
        $size         = @filesize($file);

        //ADD THESE FEW LINES
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');

        //header('Content-Type: application/force-download');
        header('Content-Disposition: attachment; filename=' . $fileId);
        header('Content-Transfer-Encoding: binary');

        //header('Content-Length: ' . $size);

        readfile($file);
        return TRUE;
    }
}

【讨论】:

    猜你喜欢
    • 2011-12-20
    • 2018-07-05
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多