What is the equivalent of force_download methode in codeIgniter 4

4.9k views Asked by At

I'm trying to allowed download file from writable path in codeIgniter 4 this code don't match

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);

I get this error : Call to undefined function

App\Controllers\force_download()

Thanks to help me

2

There are 2 answers

0
M Khalid Junaid On

If you have a direct path for your file you can use download() method from $response

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

optionally you can use setFileName() to set name for a file when sent to browser

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

Reference: Force File Download

2
ALI HAIDER On

In CI 3 we use helper to load our download functionality and the method is force_download. In CI 4 we use $response to download our file below is the code which downloads the file:

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/' this location for your file could be different so instead of this location add the location of your file