在CodeIgniter 4中等效于force_download方法

问题描述

我正在尝试允许从codeIgniter 4中的可写路径下载文件代码不匹配

helper('download');
            // read file contents
            //$data = file_get_contents(WRITEPATH.'uploads/'.$filename);
    
             $data = file_get_contents(base_url().'/uploads/'.$filename,TRUE);
            force_download($filename,$data);

我收到此错误调用未定义的函数

App\Controllers\force_download()

感谢帮助我

解决方法

如果您有文件的直接路径,则可以使用download()中的$response方法

return $response->download('/path/to/photo.jpg',null);

(可选)您可以使用setFileName()设置发送到浏览器时的文件名

return $response->download('/path/to/photo.jpg',null)->setFileName('some.jpg');

Reference: Force File Download

,

在 CI 3 中,我们使用 helper 来加载我们的下载功能,方法是 force_download。 在 CI 4 中,我们使用 $response 来下载我们的文件,下面是下载文件的代码:

public function download($id){
        $superadminModel = model('App\Models\SuperAdminModel');
        $fileinfo = $superadminModel->download($id);// get name of file using ID
        $file = ROOTPATH.'/uploads/documents/'.$File['doc'];//file location+filename
        return $this->response->download($file,null);//download file
    }

ROOTPATH.'/uploads/documents/' 您文件的这个位置可能不同,因此请添加您文件的位置,而不是这个位置