Cakephp3:从控制器返回图像内容

时间:2017-05-16 02:32:47

标签: php image cakephp cakephp-3.0

我在cakephp3中创建了一个应用程序,我想直接从控制器加载图像,并使用像user / photo / {id}这样的URL。

  public function foto($id)
{
  $usuario = $this->Usuario->get($id);
  $foto = $usuario['foto'];
  if (strpos($foto, "base64")===false) {
      $content = file_get_contents($foto,FILE_BINARY);
    $format=  getimagesize($foto);
    $this->autoRender = false;
    $this->response->type($format['mime']);

    $this->response->body($content);
  }
  else{
    $array = explode(":",$foto);
    $type = explode(";",$array[1])[0];
    $type = explode("/",$type)[1];

    $data = explode( ',', $foto );

    $this->autoRender = false;
    $this->response->type($type);
    $source = ( base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $foto)));
    $this->response->body($source);
  }
  //
  return $this->response;

}

今天,我有两种上传情况:一种是外部网址,另一种是base64编码图像 第一种情况:

  $content = file_get_contents($foto,FILE_BINARY);
    $format=  getimagesize($foto);
    $this->autoRender = false;
    $this->response->type($format['mime']);

    $this->response->body($content);

第二种情况:

$array = explode(":",$foto);
    $type = explode(";",$array[1])[0];
    $type = explode("/",$type)[1];

    $data = explode( ',', $foto );

    $this->autoRender = false;
    $this->response->type($type);
    $source = ( base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $foto)));
    $this->response->body($source);

问题在于它们都不起作用。两者都返回一个空图像。如何正确加载图像?

1 个答案:

答案 0 :(得分:0)

你忘了它:

See section sending files

因为你需要使用cakephp 3.x:

$response = $this->response->withFile('FILE_SOURCE_PATH')
return $response;

指定您需要响应并返回它。 你错误的是不要分配响应对象。