Ibexa DXP Discussions

Community discussion forum for developers working with Ibexa DXP

Links to Media Library files (/media/files/...) with a Symfony router approach

If you link from your content site to the medialibrary you can end up with broken links like ‘/media/files/foo/bar.pdf’. There are many ways to handle this case, but one way is to use the Symfony router and the eZ Platform PHP API to haddle links to outside of the site root.

This will be handled with a standard Symfony route (configuration in config/routing.yaml, or maybe config/app/routing.yml):

_media_files_download:
    path: /media/{req}
    defaults:
        _controller: App\Controller\DownloadController:mediaFileDownloadAction
    requirements:
        req: "^((?!foobar).)*$"

This route picks up anything prefixed /media/ and passes that to a controller action that then does a query based on the path using the injected urlAliasService and locationServices and returning a RedirectResponse to the download URL of the file.

Something along the lines of this should work:

<?php

namespace App\Controller;

use eZ\Publish\API\Repository\LocationService;
use eZ\Publish\API\Repository\URLAliasService;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

class DownloadController extends AbstractController {

    private $locationService;
    private $urlAliasService;

    public function __construct(
        LocationService $locationService,
        URLAliasService $urlAliasService,
    )
    {
        $this->locationService = $locationService;
        $this->urlAliasService = $urlAliasService;

	public function mediaFileDownloadAction(Request $request){

	    $urlAlias = $this->urlAliasService->lookup($request->getPathInfo());
	    $location = $this->locationService->loadLocation($urlAlias->destination);

	    // only allow downloads of file content type
	    if($location->contentInfo->contentTypeId == SELF::FILE_CONTENT_TYPE_ID){
	        $file = $location->getContent()->getFieldValue('file');
	        return new RedirectResponse($file->uri,301);
	    }

	    throw $this->createNotFoundException('File not found');

	}