【问题标题】:CodeIgniter force_download function does not workCodeIgniter force_download 功能不起作用
【发布时间】:2018-06-02 15:59:12
【问题描述】:

在下面的代码示例中,我正在调用下载页面。但是,force_download 不起作用。没有重定向,它停留在同一页面上,因为我将该页面称为index.php/sample/download。只有网址在变化。但是没有触发下载。我也不能直接调用页面/sample/download。虽然我为index.php(index_page)指定了所需的配置,但是如果我没有将下载链接指定为/sample/index.php/sample/download,则会返回404错误。

应用程序/控制器/Sample.php

class Sample extends MY_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper(array('form', 'url_helper', 'download'));           
        $this->load->model('Sample_model');
    }

    public function index() {
        $data = $this->getData();
        $this->load->view('sample/view', $data);
    }

    public function download() {
        $data = 'Here is some text!';
        $name = 'mytext.txt';
        force_download($name, $data);
    }
}

application/views/sample/view.php

<a href="<?php echo base_url(); ?>index.php/sample/download">Download file</a>

application/config/config.php

$config['index_page']   = '';
$config['uri_protocol'] = 'REQUEST_URI';

application/config/routes.php

$route['default_controller']    = 'Sample';
$route['404_override']          = '';
$route['translate_uri_dashes']  = FALSE;
$route['sample']                = 'sample/index';
$route['sample/download']       = 'sample/download';

【问题讨论】:

  • 路由不工作或force_download?
  • 可以尝试$name = FCPATH .'downloads/mytext.txt';在主目录中创建一个名为downloads的文件夹,确保文件夹权限为0777,或者可以将exit()放在force_download()下

标签: php codeigniter force-download


【解决方案1】:

通过以下方式更新您的代码,

应用程序/控制器/Sample.php

class Sample extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper(array('form', 'url_helper', 'download'));           
        $this->load->model('Sample_model');
    }

    public function index() {
        //$data = $this->getData();                 // NOT DEFINED
        $this->load->view('sample/view', $data);
    }

    public function download() {
        $data = 'Here is some text!';
        $name = 'mytext.txt';
        force_download($name, $data);
    }
}

application/views/sample/view.php

<a href="<?= base_url('sample/download'); ?>">Download file</a>

application/config/routes.php

$route['default_controller']    = 'sample';
$route['404_override']          = '';
$route['translate_uri_dashes']  = FALSE;
$route['sample']                = 'sample/index';
$route['sample/download']       = 'sample/download';

确保您的.htaccess 文件如下所示

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
</IfModule>

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    相关资源
    最近更新 更多