【问题标题】:symfony display image thumbnail for file in private directorysymfony 显示私有目录中文件的图像缩略图
【发布时间】:2023-01-25 19:54:20
【问题描述】:

我有 Symfony 6.2 应用程序,其中登录用户可以将图像上传到服务器。因为图像是非公开的,所以我将这些图像上传到 /var/images 目录。 在 config/services.yaml 我有

parameters:
    card_directory: '%kernel.project_dir%/var/images'

以及我使用的上传服务

    App\Service\ImageUploader:
        arguments:
            $targetDirectory: '%card_directory%'

上传图片是功能。 但现在我需要将这些图像提供给用于生成 4 列缩略图画廊的树枝模板。我应该如何在树枝模板中生成此图像的路径?

最后,我将此代码用于服务器私有图像,并使用 Controller for Card 实体,它具有图像

<?php

namespace App\Controller;

use App\Entity\Card;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\Routing\Annotation\Route;

class ServePrivateImageController extends AbstractController
{
    /**
     * Returns a private image for card file for display.
     *
     * @Route("/serve-private-image/{id}", name="serve_private_image", methods="GET")
     * @param Card $card
     * @return BinaryFileResponse
     */
    public function privateImageServe(Card $card): BinaryFileResponse
    {
        return $this->fileServe($card->getImage());
    }
    /**
     * Returns a private file for display.
     *
     * @param string $path
     * @return BinaryFileResponse
     */
    private function fileServe(string $path): BinaryFileResponse
    {
        $absolutePath = $this->getParameter('card_directory') . '/' . $path;

        return new BinaryFileResponse($absolutePath);
    }
}

【问题讨论】:

  • 正如您所说,目录(以及图像)不是公开的 - 您无法生成路径。因此,您需要创建一个控制器来获取和提供这些图像。

标签: symfony gallery private


【解决方案1】:

要回答您的问题,您只需在树枝中参考您的路线。

<div class="row">
{% for file in files %}
<div class="col-md-3">
<img src="{{ path('serve_private_image', {id: file.id}) }}" />
</div>
{% endfor %}

但就提供调整大小的图像而言,LiipImageBundle 可以满足您的需求,甚至更多:

https://github.com/liip/LiipImagineBundle

虽然设置需要几分钟(因为与 flysystem 的集成),但一旦它开始工作,您甚至可以将(安全的)图像保存在 s3 上,它会处理所有下载和本地缓存、旋转调整大小的问题等。

【讨论】:

    猜你喜欢
    • 2012-11-30
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2012-04-18
    • 2016-06-13
    相关资源
    最近更新 更多