使用 ZF2 强制下载 [英] force download using ZF2

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

问题描述

我正在尝试使用 ZF2 进行强制下载.这是我的代码片段

I am trying to do force download using ZF2. Here is the snippet to my code

 use Zend\Http\Request;
 .....
   public function downloadAction() {
     $response = new Request();
    $response->setHeaders(Request::fromString("Content-Type: application/octet-stream\r\nContent-Length: 9\r\nContent-Disposition: attachment; filename=\"ultimate_remedy_readme.txt\""));


}

现在我收到这个错误

/var/www/whowantsmymoney/vendor/zendframework/zendframework/library/Zend/Http/Request.php:88

留言:

A valid request line was not found in the provided string

堆栈跟踪:

#0 /var/www/whowantsmymoney/module/Admin/src/Admin/Controller/LanguageController.php(93): Zend\Http\Request::fromString('Content-Type: a...')

推荐答案

此代码应该可以帮助您进行简单的文件下载.

This code should help you for a simple file download.

public function downloadAction() {
    $fileName = 'somefile';

    if(!is_file($fileName)) {
        //do something
    }

    $fileContents = file_get_contents($fileName);

    $response = $this->getResponse();
    $response->setContent($fileContents);

    $headers = $response->getHeaders();
    $headers->clearHeaders()
        ->addHeaderLine('Content-Type', 'whatever your content type is')
        ->addHeaderLine('Content-Disposition', 'attachment; filename="' . $fileName . '"')
        ->addHeaderLine('Content-Length', strlen($fileContents));


    return $this->response;
}

我想这段代码还有很多不足之处,但应该可以在简单的情况下工作,就像我的一样.我不确定您如何处理分块读取文件.也许其他人可以提供一些启发?

I imagine this code leaves a lot to be desired, but should work in simple cases, as was mine. I'm not sure how you might handle reading the file in chunks. Maybe somebody else could shed some light?

编辑 - 发送流

我在此处添加了此信息以供参考.这可能是强制下载的更好方法,因为它会使用更少的内存.

I've added this here for informational purposes. It is probably the better way to force downloads as it will use much less memory.

public function downloadAction() {
    $fileName = 'somefile';

    $response = new \Zend\Http\Response\Stream();
    $response->setStream(fopen($fileName, 'r'));
    $response->setStatusCode(200);

    $headers = new \Zend\Http\Headers();
    $headers->addHeaderLine('Content-Type', 'whatever your content type is')
            ->addHeaderLine('Content-Disposition', 'attachment; filename="' . $fileName . '"')
            ->addHeaderLine('Content-Length', filesize($fileName));

    $response->setHeaders($headers);
    return $response;

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

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