在 codeigniter 中没有 force_download 图像和 pdf 文件

Not force_download with images and pdf files in codeigniter

你好朋友我有一个关于 force_download 功能的问题,我在网站上有一个上传表格,我正在使用这个功能下载我上传的数据并且它有效

public function download($file)
    {
        force_download('./uploads/'.$file, NULL);
    }

但是你知道pdf,png,jpg文件可以在导航器中直接看到,如果你想要你不需要下载它但是如果我使用这个功能所有文件都被下载了,我怎么能得到它?

我尝试使用直接 link 到我的上传文件夹,但这是可能的,因为我有一个 .htaccess 文件拒绝访问以防止登录用户只能下载一些东西。

正如我已经写过的,在 download/preview 代码之前检查 if elseif else 或什至更好的 switch case 块并检查文件扩展名。类似于:

public function download($file)
{
    //get the file extension
    $info = new SplFileInfo($file);
    //var_dump($info->getExtension());

    switch ($info->getExtension()) {
        case 'pdf':
        case 'png':
        case 'jpg':
            $contentDisposition = 'inline';
            break;
        default:
            $contentDisposition = 'attachment';
    }

    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        // change inline to attachment if you want to download it instead
        header('Content-Disposition: '.$contentDisposition.'; filename="'.basename($file).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
    }
    else echo "Not a file";
}