繁体   English   中英

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

[英]Cakephp3: Return image content from controller

我有一个在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);

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

你忘了它:

请参阅发送文件部分

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM