Antenne
Antenne

Reputation: 61

ZF2 - Display image in view based on full path

I have managed to upload image file in ZF2 and store full path in the database. Path looks like this:

/home/ubuntu/NetBeansProjects/project/data/upload/event_5554a7b600c0f.jpg

Project structure is a Zend Skeleton application:

project data upload event_5554a7b600c0f.jpg module public

In my view I call:

     <img src="<?php echo $event->getImage(); ?>" class="img-thumbnail" alt="<?php echo $event->getTitle(); ?>" width="304" height="236"> </td>

$event->getImage() return the full file location as stated earlier.

If I store the same image in project public img upload event_5554a7b600c0f.jpg

and store /img/upload/event_5554a7b600c0f.jpg as path it works.

I have two question: 1. What is a good policy, to store uploaded image files in the publi/img folder or in top level data/uploads folder? 2. If it is a better policy to store the files in data/uploads how can I display the image?

Thank you!

Upvotes: 3

Views: 2471

Answers (2)

Ujjwal Ojha
Ujjwal Ojha

Reputation: 1360

I have created a module HtImgModule for doing image manipulation in Zend Framework 2.

Here is an example to simply output an image:

namespace Applicaton\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use HtImgModule\View\Model\ImageModel;

class MyController extends AbstractActionController
{
    public function displayImageAction()
    {
        return new ImageModel('path/to/image');
    }
}

So, it is not absolutely necessary to store images in public folder. But, there are performance penalty. Fortunately, HtImgModule is flexible enough to cache the image to the web root so that the cached image would be served directly from the file system. Take a look at the docs of HtImgModule.

Upvotes: 3

Finbarr
Finbarr

Reputation: 486

If the image is public and you are happy that anyone on the web can potentially see it it is easiest to keep it in the public folder.

When you might consider putting it in the data directory is if you need to secure the image behind username / password or ACL, etc. In order to get this to work you could create a controller to access the image and stream it in a response using something like this;

$filesize = filesize($directory.$fileName);
$response = new \Zend\Http\Response\Stream();
$response->setStream(fopen($directory.$fileName, 'r'));
$response->setStatusCode(200);
$headers = new \Zend\Http\Headers();
$headers->addHeaderLine('Content-Type', $mimeType)
    ->addHeaderLine('Content-Disposition', 'attachment; filename="' . $fileName . '"')
    ->addHeaderLine('Content-Length', $filesize);

$response->setHeaders($headers);

return $response;

This I imagine does add extra load to your server.

Upvotes: 0

Related Questions