Search code examples
codeigniter-4

how to display uploaded file from writable/uploads in codeigniter 4


In Codeigniter4 how to show the path of uploaded file from the writable/uploads folder?

The file may be an image, doc, pdf or CSV. I upload the file using the below code and store it in DB.

$file->move(WRITEPATH . 'uploads', $fileName);

all uploaded records are listed on a page and have to open the uploaded CSV/excel in a new tab from the listing page.

but I did not get the path from the writable/uploads folder to open in a new tab.

<?=WRITEPATH.'uploads/'.$allList->documentCsv?>

when I copy the link and open it on a tab it downloaded.

Please explain how to show the path.

Thanks


Solution

  • Based on your clarification. I get this summary.

    You want to show file binary value but instead of download you wanna show it in browser.

    I have this code for you

    public function showFile()
    {
        helper("filesystem");
        $path = WRITEPATH . 'uploads/';
        $filename = 'logo-at.png';
    
        $fullpath = $path . $filename;
        $file = new \CodeIgniter\Files\File($fullpath, true);
        $binary = readfile($fullpath);
        return $this->response
                ->setHeader('Content-Type', $file->getMimeType())
                ->setHeader('Content-disposition', 'inline; filename="' . $file->getBasename() . '"')
                ->setStatusCode(200)
                ->setBody($binary);
    }
    

    The supported extension will show the file value in browser. If not, it will downloaded.

    Reference in documentation:

    1. https://codeigniter4.github.io/CodeIgniter4/libraries/files.html#getting-a-file-instance
    2. https://codeigniter4.github.io/CodeIgniter4/outgoing/response.html#http-responses