force download using ZF2

前端 未结 2 1660
南笙
南笙 2020-12-24 08:16

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

 use Zend\\Http\\Request;
 .....
   public function downloadAction() {
     $resp         


        
2条回答
  •  甜味超标
    2020-12-24 09:01

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

    Full headers stack:

    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;
    }
    

提交回复
热议问题