Codeigniter 强制下载文件 [英] Codeigniter Force download files
问题描述
通过阅读 Codeigniter 文档,我使用以下代码从我的服务器强制下载文件.
By going through the Codeigniter documentation, I am using the following code to force download files from my server.
function download($file_id){
$file = $this->uploadmodel->getById($file_id); //getting all the file details
//for $file_id (all details are stored in DB)
$data = file_get_contents($file->full_path); // Read the file's contents
$name = $file->file_name;;
force_download($name, $data);
}
代码是用于图像的工作文件,但是当涉及 PDF 文件时,它不起作用.我尚未针对所有文件扩展名对其进行测试,但由于它不适用于 PDF,因此它可能不适用于其他各种文件类型.有什么解决办法吗?
The code is working file for images, but when it comes with the case of PDF files, it is not working. I have not tested it for all file extensions, but since it is not working for PDF, it might not work for other various file types. Any solution?
推荐答案
我也遇到过类似的问题.我认为问题在于发送到浏览器的某些 mime 和标头.我最终使用了我在这里找到的代码 http://taggedzi.com/articles/display/forcing-downloads-through-codeigniter.使用下面的函数代替 force_download.到目前为止,它对我有用.
I've had similar problems. I think the problem resides in certain mime's and headers sent to the browser(s). I've end up using the code I found here http://taggedzi.com/articles/display/forcing-downloads-through-codeigniter. Use the function below instead of force_download. It has worked for me so far.
function _push_file($path, $name)
{
// make sure it's a file before doing anything!
if(is_file($path))
{
// required for IE
if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }
// get the file mime type using the file extension
$this->load->helper('file');
$mime = get_mime_by_extension($path);
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($path)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: '.$mime); // Add the mime type from Code igniter.
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($path)); // provide file size
header('Connection: close');
readfile($path); // push it out
exit();
}
}
希望有帮助.
这篇关于Codeigniter 强制下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!