如何在Symfony2控制器中获取文件的绝对路径?

3

我希望发送一封带有附件的电子邮件,因此需要获取PDF文件的绝对路径。

我在控制器中尝试了以下代码:

$this->get('templating.helper.assets')->getUrl('MyDoc.pdf', 'doc');

但是这会返回:
/bundles/MyBundle/doc/MyDoc.pdf?v=1

这是没有域名的网页访问路径。但我需要从磁盘根目录开始的真实路径,就像下面的例子一样。这可能吗?谢谢。

以下是示例:

/var/www/html/example/index.html

/home/MyAccount/public_html/web/src/company/MyBundle/Resources/public/doc/MyDoc.pdf
3个回答

10

$this->get('templating.helper.assets') 资源助手是关于HTTP URI,而不是目录路径。然而,你可以通过以下方式轻松获取正确的绝对目录 web 路径:

$appPath = $this->container->getParameter('kernel.root_dir');
$webPath = realpath($appPath . '/../web');

$webPath 应该返回类似于这样的内容:

/home/martins/www/symfony-project/web

4

以下是不同应用程序的URL/URI路径的快速参考。

使用Symfony\Component\HttpFoundation\Request组件,可以通过许多不同的方式调用它。

考虑此链接http://dev.col.com/app_dev.php/my-route?bar=1&foo=bar

$r = $this->getRequest();
$r->getClientIp()                   127.0.0.1
$r->getScriptName()                 /app_dev.php
$r->getPathInfo()                   /my-route
$r->getBasePath()                   ''
$r->getBaseUrl()                    /app_dev.php
$r->getScheme()                     http
$r->getPort()                       80
$r->getHttpHost()                   dev.col.com
$r->getRequestUri()                 /app_dev.php/my-route?bar=1&foo=bar
$r->getBaseServerUrl()              http://dev.col.com
$r->getUri()                        http://dev.col.com/app_dev.php/my-route?bar=1&foo=bar
$r->getUriForPath("/other-path")    http://dev.col.com/app_dev.php/other-path
$r->getQueryString()                bar=1&foo=bar
$r->isSecure()                      false
$r->getHost()                       dev.col.com
$r->getMethod()                     GET
$r->isXmlHttpRequest()              false

或者您也可以使用Twig来实现。例如:
<div>
    <a href="{{ job.url }}">
        <img src="{{ app.request.scheme ~ '://' ~ app.request.host }}{{ asset(job.webPath) }}" alt="{{ job.company }} logo" />
    </a>
</div>

<div>
    <a href="{{ job.url }}">
        <img src="{{ app.baseServerUrl }}{{ asset(job.webPath) }}"alt="{{ job.company }} logo" />
    </a>
</div>

3
use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->files()->in("dir")->name("name.file");

foreach ($finder as $file) {
    // Dump the absolute path
    var_dump($file->getRealPath());
}

来自文档: http://symfony.com/doc/current/components/finder.html

该组件允许您在目录结构中搜索文件。它提供了一个流畅且易于使用的API,可以通过不同的标准(例如名称、类型、大小等)过滤搜索结果。此外,它还可以递归地遍历子目录。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接