Zend Framework 2文件下载 [英] Zend Framework 2 file download

查看:144
本文介绍了Zend Framework 2文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Zend\Filter\File\RenameUpload 将文件上传到文件夹 ./ data / uploads / code>过滤器。

I made a form to upload files to the folder ./data/uploads using the Zend\Filter\File\RenameUpload filter.

这个工作就像一个魅力。我现在的问题是如何提供这个文件给用户下载?

This is working like a charm. My problem now is how do I provide this file to users download it?

我认为这样会是:

$ response-> setContent(file_get_contents('./ data / uploads / file.png'));

但是我想知道最好的方法是什么。

But I want to know what is the best way to do this.

推荐答案

感谢@henrik的回复,但他的答案中却遗漏了几个重要的标题。小心点。

Thanks to @henrik for response, but several important headers are missing in his answer. Be careful of that.

全标题栈:

public function downloadAction() {
    $file = 'path/to/file';
    $response = new \Zend\Http\Response\Stream();
    $response->setStream(fopen($file, 'r'));
    $response->setStatusCode(200);
    $response->setStreamName(basename($file));
    $headers = new \Zend\Http\Headers();
    $headers->addHeaders(array(
        'Content-Disposition' => 'attachment; filename="' . basename($file) .'"',
        'Content-Type' => 'application/octet-stream',
        'Content-Length' => filesize($file),
        'Expires' => '@0', // @0, because zf2 parses date as string to \DateTime() object
        'Cache-Control' => 'must-revalidate',
        'Pragma' => 'public'
    ));
    $response->setHeaders($headers);
    return $response;
}

这篇关于Zend Framework 2文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆