php 如何创建链接以在 symfony2 中下载生成的文档?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10122807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:26:04  来源:igfitidea点击:

How to create a link to download generated documents in symfony2?

phpsymfonytwig

提问by David 'the bald ginger'

Documents are created by the system and saved to the folder /web/downloads. I have created a view to display links which will allow a user to download the files, should the user click the links. (standard click to download feature)

文件由系统创建并保存到文件夹/web/downloads。我创建了一个视图来显示链接,如果用户单击链接,它将允许用户下载文件。(标准点击下载功能)

I am new to Symfony2 and am getting around the whole routing/controller concept, but how would one create a link to such files while still adhering to the MVC? Does one need to set up routing with a controller or does twig have features which allow it etc.

我是 Symfony2 的新手并且正在解决整个路由/控制器概念,但是如何在仍然坚持 MVC 的同时创建指向此类文件的链接?是否需要使用控制器设置路由或树枝是否具有允许它等的功能?

PS: I have read questions such as How to create a download link in Symfony2?but i do not get if they did something in the routing or just added links etc.

PS:我已经阅读了诸如如何在 Symfony2 中创建下载链接之类的问题?但我不明白他们是否在路由中做了什么或者只是添加了链接等。

Thank you,

谢谢,

采纳答案by Christian Riesen

Let's make a sample.

让我们做一个样本。

Say your project lives in /www/, so /www/web/ is the document root of your symfony2 application. Now everything you try to access that is in /www/web/ over http://server/will show up.

假设您的项目位于 /www/,所以 /www/web/ 是您的 symfony2 应用程序的文档根目录。现在,您尝试通过http://server/访问 /www/web/ 中的所有内容都将显示出来。

/www/web/downloads/file.zip would be reachable at http://server/downloads/file.zipby default.

默认情况下,/ www/web/downloads/file.zip 可以通过http://server/downloads/file.zip访问。

回答by Mun Mun Das

Sample implementation would be,

示例实现将是,

Create a route,

创建路线,

download_route:
    pattern:  /download/{filename}
    defaults: { _controller: YourBundle:Controller:download }

And then in your controller,

然后在你的控制器中,

public function downloadAction($filename)
{
    $request = $this->get('request');
    $path = $this->get('kernel')->getRootDir(). "/../web/downloads/";
    $content = file_get_contents($path.$filename);

    $response = new Response();

    //set headers
    $response->headers->set('Content-Type', 'mime/type');
    $response->headers->set('Content-Disposition', 'attachment;filename="'.$filename);

    $response->setContent($content);
    return $response;
}

For generating download link check Generating urlssection of the doc.

要生成下载链接,请检查文档的生成网址部分。

回答by Andy

This is the best solution i came up with so far, it allows you to serve downloads from outside of your "/var/www/web/" folder, which makes the file not accessible without running this script used to serve the file.

这是迄今为止我想出的最佳解决方案,它允许您从“/var/www/web/”文件夹之外提供下载,这使得如果不运行用于提供文件的脚本就无法访问该文件。

This way you can check if the downloader has permission to download the file he wants.

这样你就可以检查下载者是否有权限下载他想要的文件。

In this example i used "/var/www/downloads/" where i store all files i want to serve as a download:

在这个例子中,我使用了“/var/www/downloads/”来存储我想要作为下载的所有文件:

/**
 * http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/BinaryFileResponse.html
 */
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class OfflineToolController extends Controller
{
    /**
     * @return BinaryFileResponse
     */
    public function downloadAction()
    {
        $path = $this->get('kernel')->getRootDir(). "/../downloads/"; 
        $file = $path.'my_file.zip'; // Path to the file on the server
        $response = new BinaryFileResponse($file);

        // Give the file a name:
        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,'my_file_name.zip');

        return $response;
    }

}

source: docs: http://symfony.com/doc/current/components/http_foundation/introduction.html

来源:文档:http://symfony.com/doc/current/components/http_foundation/introduction.html

(should work on versions above 2.2)

(应该适用于 2.2 以上的版本)

回答by schizoskmrkxx

Just adding the path of the file to the hrefattribute didn't work for me.

只是将文件的路径添加到href属性中对我不起作用。

When clicked, it just displays the file without really downloading it.

单击时,它只显示文件,而没有真正下载它。

What worked for me though is adding a downloadattribute to my link which is an HTML5 attribute. Just add the attribute like so:

对我有用的是向download我的链接添加一个属性,这是一个 HTML5 属性。只需像这样添加属性:

<a href="path/to/file" download>Download Link</a>

Upon clicking the link, it will just download the file without any server side code.

单击链接后,它只会下载文件,而无需任何服务器端代码。

You can also assign a value to the downloadattribute.

您还可以为该download属性分配一个值。

<a href="path/to/file" download="filename.txt">Download Link</a>

The value of the downloadattribute will be used as the file name of the downloaded file instead of the one used while it was stored on the server.

download属性的值将用作下载文件的文件名,而不是存储在服务器上时使用的文件名。

I followed the tutorialin the Symfony website regarding file upload handling. I found it helpful when I was figuring out how to make a download link for the file. I just added a method to the Documententity called getDownloadFileName()which just returns the file name I want to assign to the downloadattribute.

我遵循了Symfony 网站上关于文件上传处理的教程。当我弄清楚如何为文件制作下载链接时,我发现它很有帮助。我刚刚向Document被调用的实体添加了一个方法,它只getDownloadFileName()返回我想分配给download属性的文件名。

So basically, this is how I implemented it on my Symfony project's twig template

所以基本上,这就是我在我的 Symfony 项目的树枝模板上实现它的方式

<a href="{{ asset(file.webPath) }}" download="{{ file.downloadFileName }}">
Download Link
</a>

回答by lio89

Don't know if this fits you, but keep this another ultra simple alternative in mind:

不知道这是否适合您,但请记住另一个超简单的替代方案:

i.e. in your view:

即在您看来:

<a class='north' href="{{ asset('bundles/TP/Resume.pdf') }}" target="_blank" title="Download.pdf"><img src="{{ asset('bundles/TP/images/icn-save.jpg') }}" alt="Download the pdf version" /></a>

It opens the file, and the user has the decision if he wants to print it, download it... etc

它打开文件,用户可以决定是否要打印、下载...等