force download using ZF2

前端 未结 2 1659
南笙
南笙 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 08:42

    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?

    Edit - Sending streams

    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;
    

提交回复
热议问题