如何通过强制下载下载图像文件

时间:2014-08-18 13:21:01

标签: php download

我正在尝试在CI中下载图像文件,但在打开下载图像文件时出错。需要帮助:(

$file_name = $_GET['file_name'];
            $file_path =  "./ups_printimages/".$file_name;
            if(file_exists($file_path))
            {
                $this->load->helper('download');
                $data = file_get_contents($file_path); // Read the file's contents
                $name = 'ups_label.png';
                force_download($name, $data);
            }
            else
            {
                echo "file does not exist";
            }

2 个答案:

答案 0 :(得分:2)

GOD。找到解决方案:))

if(!file)
    {
         File doesn't exist, output error
         die('file not found');
    }
    else
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        ob_clean();
        flush();
        readfile($file);
        exit;
     }

答案 1 :(得分:0)

使用标头强制下载。使用以下代码

 $file_name = $_GET['file_name'];
                $file_path =  "./ups_printimages/".$file_name;
                if(file_exists($file_path))
                {
                 header('Content-Type: image/jpeg');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"" . basename($file_name) . "\""); 
    readfile($file_path); 
                }
                else
                {
                    echo "file does not exist";
                }

希望这有助于yoiu