【问题标题】:Not force_download with images and pdf files in codeigniter不是在 codeigniter 中使用图像和 pdf 文件强制下载
【发布时间】:2017-02-10 10:57:49
【问题描述】:

朋友们好,我有一个关于 force_download 功能的问题,我在网站上有一个上传表单,我正在使用这个功能来下载我上传的数据并且它可以工作

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

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

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

【问题讨论】:

  • 首先你必须检查文件类型。然后,采取相应的行动。检查this code 如何操作内容配置。
  • 感谢朋友这工作现在我可以直接看到 pdf 文件,如果我想不下载它,有没有类似于 png,jpg,mp4...的东西?还有其他文件类型可以直接在浏览器中打开

标签: php .htaccess codeigniter force-download


【解决方案1】:

正如我已经写过的,在下载/预览代码之前检查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";
}

【讨论】:

    猜你喜欢
    • 2013-01-27
    • 2021-01-27
    • 2014-11-19
    • 1970-01-01
    • 2011-05-12
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    相关资源
    最近更新 更多