简体   繁体   中英

Symfony Gaufrette - Download or Read Image from filesystem and show it in twig

my question is simple. I use Symfony framework and Gaufrette filesystem (KnpGaufretteBundle) and I allready saved files (images) in filesystem.

Now I want show that images in twig. In controller I get the file:

$image = $filesystem->get($fie_key);

In variable $image is Gaufrette\\File object. I would like to display that image in twig in <img> tag. But i don't know how to do that. Thank you for help

Gaufrette is a file system abstraction library, seems like it doesn't implement any routing options for the files.

First option is creating a public route for your Gaufrette file system folder and reach the files as @Broncha mentioned.

The other option is; You can use Base64 encode to show images in the template, without passing a url for the image.

For eq

<?php
require_once('vendor/autoload.php');

use Gaufrette\Filesystem;
use Gaufrette\File;
use Gaufrette\Adapter\Local as LocalAdapter;

$adapter = new LocalAdapter('files');
$filesystem = new Filesystem($adapter);

$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array(
    'cache' => 'tmp',
));
//Probably the top part is redundant for you
//I've just set up a local twig and Gaufrette environment.

$file_key = "shareimage.png";
$file = $filesystem->get($file_key);
echo $twig->render('index.html', array('imageContent' => "data: ".$file->getMtime().";base64,".base64_encode($file->getContent())));

This is the simple template file;

<html>
    <body>
        <img src="{{imageContent}}" alt="Image" />
    </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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