有没有办法让一个Codeigniter控制器返回一个图像

有没有办法让一个Codeigniter控制器返回一个图像

本文介绍了有没有办法让一个Codeigniter控制器返回一个图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个控制器的方法,而不是返回一个字符串或视图,返回一个图像(是JPG,PNG等)。例如,我不想以$ this-> load-> view('folder / special_view.php)结束,而是像$ this-> load-> image('images / gorilla.png') ,并有它,所以如果我的用户去的控制器,他们会看到一个图像,如果他们去一个正常的.png或jpeg。我可以设置标题,以便它期望一个不同的MIME?

I was wondering if there was a way for a controller to, instead of returning a string, or a view, return an image (be it JPG, PNG etc). For example, instead of ending with a $this->load->view('folder/special_view.php), I'd like to do something like $this->load->image('images/gorilla.png'), and have it so if my user were to go to that controller they would see an image as if they'd gone to a normal .png or jpeg. Can I set the headers so it expects a different MIME? Example code of this would be fantastic.

这将需要我永远解释为什么我需要这个,但它涉及到一个预制CMS到codeigniter,并有它需要证明事情是真实的。非常感谢!

It would take forever for me to explain why I need this, but it involves bringing a premade CMS into codeigniter, and having it need certian things to be true. Thank you so much!

推荐答案

确实可以,使用这个而不是 $ this-> load - > view()

sure you can, use this instead of $this->load->view()

$filename="/path/to/file.jpg"; //<-- specify the image  file
if(file_exists($filename)){
  header('Content-Length: '.filesize($filename)); //<-- sends filesize header
  header('Content-Type: image/jpg'); //<-- send mime-type header
  header('Content-Disposition: inline; filename="'.$filename.'";'); //<-- sends filename header
  readfile($filename); //<--reads and outputs the file onto the output buffer
  die(); //<--cleanup
  exit; //and exit
}

当然,你需要交换mime类型case该文件是一个png或gif

of course, you need to swap the mime-type in case the file is a png or gif

这篇关于有没有办法让一个Codeigniter控制器返回一个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 06:01