Chrome 如果大小 > n Kb,则打开文件而不是下载

Chrome opens file instead of downloading if size > n Kb

我必须制作一个 php 生成的文件才能下载,不能在浏览器中打开。虽然它很小 (1-2 kb) 文件通常保存在下载中,但过了一段时间后,Chrome 开始打开它而不是下载。

控制器代码如下:

public function download($format, $str)
{
    $get_string = rawurldecode($str);
    parse_str($get_string, $get_array);

    $webinar_id = $get_array['webinar_id'];
    unset($get_array['webinar_id']);

    $date = new DateTime();

    $this->output->set_header('Content-type: text/plain');
    $this->output->set_header('Content-Disposition: attachment; filename=Segmentation ' . $date->format('Y-m-d H:i:s') . '.' . $format);

    if (! empty($get_array))
    {
        echo $this->segmentation_model->do_query($webinar_id, $get_array, $format);
    }
}

你试过加强制下载吗content-typeheader?

可以这样做:

$this->output->set_header("Content-Type: application/force-download");

header("Content-Type: application/force-download");

使用 CodeIgniter 助手的正确答案:

$txt = 'file content';
$this->load->helper('download');
force_download('File ' . date('Y-m-d H:i:s') . '.txt', $txt);