2017-05-16 9 views
1

cakephp3で作成したアプリケーションを持っていて、コントローラから直接user/photo/{id}のようなURLで画像をロードしたいと思います。 base64でエンコードされた画像によって、外部URLずつ、およびその他の 最初のケース:Cakephp3:コントローラからの画像内容を返す

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; 

} 

今日、私はアップロードの2例持つ

$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); 

問題はそれらのどれも働かないことです。どちらも空のイメージを返します。画像を正しく読み込むにはどうしたらいいですか?

+0

なぜファイルの内容を配列に読み込むのですか?そして、なぜあなたはそれをシリアル化しますか? btw、PHP [** stream wrappers **](http://php.net/manual/en/wrappers.php)は 'data:'をそのままの状態でサポートしています。つまり、いくつかのデバッグを行い、あなたが実際に作業している値をチェックし、ブラウザのネットワークコンソールでサーバの応答の詳細を確認してください。 – ndm

+0

バイナリモードでfile_get_contentsを読んでいました。私はファイルを保存することができました。しかし、私はケーキの中身をコンテンツとして使用しようとしたとき、それは仕事をしませんでした。そして、データはbase64エンコードされたファイルで私の問題を解決できますが、外部URLは解決できません。 – vicebas

答えて

0

あなたはそれを忘れて:

See section sending files

あなたが必要なCakePHPの3.xの使用原因:

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

は、あなたが応答する必要があり、それを返すことを割り当てます。 あなたはエラーが応答オブジェクトを割り当てていません。

+0

は、あなたが返す必要のある身体、状態、タイプまたはファイルと同じです。 –

+1

これはcakephp 3.4です。 3.4より前には、この方法を使用する必要がありました。 // 3.4.0より前 $ file = $ this->添付ファイル - > getFile($ id); $ this-> response-> file($ file ['path']); //コントローラがレンダリングしようとしないように応答を返します //ビュー。 return $ this-> response; – vicebas

関連する問題