display image from database

故事扮演 提交于 2019-12-11 14:00:06

问题


Table User

image(blob type)  
------------------------------
0xFFD8FFE0     

myController

function displayImage($id)
{

        $this->autoRender = false;


        $peoples=TableRegistry::get('peoples');      
        $peoples=$peoples->getRecord([ 'image'])->first();   

        header('Content-Type: image/jpeg');

         echo $peoples['image']; 
}

Model

function getRecord($fields)
{
    return $this->find('all')->select($fields);
}

But when I set this:

<img id="imgPreview" src="displayImage/30">

the image does not show anything. When I use myController/displayImage/30 this shows Resource id #170 to me!

Why is this? How can I display the image?


回答1:


You need to read from that returned resource to get the actual content (image data)

public function displayImage($id)
{ 
    // ... 
    echo stream_get_contents($peoples['image']);
}

Here is modified working example of your method. I've assumed, that you have model named Peoples with property image(BLOB) and $id refers to some row in an underlying table

public function displayImage($id) {
    $table = TableRegistry::get('Peoples');
    $entity = $table->get($id);

    $this->response->type('jpg');
    $this->response->body(stream_get_contents($entity->image));

    return $this->response;
}



回答2:


You're trying to fetch an image from a user ID?

If that is the case

$peoples = TableRegistry::get('Peoples');
$peoples->find('all');
$peoples->matching('Users', function($q) use($id) {
   return $q->where(['Users.id' => $id]);
});

$result = $peoples->first();
$result->users[0]->image;



回答3:


If your question is about struggling with the right HTML code to upload images. For that you just have to give to that uploading field in database table column varchar type and then in the view where to upload the image from give it a file type. Something like:

   <?php
        echo $this->Form->input('your_column_name', [ 'type' => 'file']); 
    ?>

But if your question is about not being able to retrieve or send to index.ctp or to a frontend view the uploaded image, then your solution is here: How to retrieve in cakephp3.7 the name as string of an image uploaded trough a form with blob column into a mysql database?



来源:https://stackoverflow.com/questions/30557568/display-image-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!