Home > other >  Symfony 4 : Download file using ajax
Symfony 4 : Download file using ajax

Time:02-10

I'm trying to download file using Ajax. My request actually returns 200 status but the file can't be downloaded

The action used to manage download file :

 /**
 * @Route("/download/documents/{filename}", name="download_documents")
 */
public function download(string $filename, FileHelper $fileHelper, KernelInterface $appKernel) :Response
{
    try {
        if (! $filename) {
            $array = array (
                'status' => 0,
                'message' => 'File does not exist'
            );
            return new JsonResponse ( $array, 200 );
        }

        $pathFile = $appKernel->getProjectDir().$this->getParameter('app.directory.upload').$filename;
        
        $file_with_path = $appKernel->getProjectDir().$this->getParameter('app.directory.upload').$filename;
        $disposition = HeaderUtils::makeDisposition(
            HeaderUtils::DISPOSITION_ATTACHMENT,
            $filename
        );
        $response = new BinaryFileResponse ( $file_with_path );
        $response->headers->set('Content-Disposition', $disposition);
        $response->headers->set('Content-Type', 'application/octet-stream');
        $response->headers->set('Content-Description', 'File Transfer');
        $response->headers->set('Content-Transfer-Encoding', 'binary');
        $response->headers->set('Expires', '0');
        $response->headers->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
        $response->headers->set('Pragma', 'public');
        $response->headers->set('Content-Length', filesize($pathFile));
        $response->sendContent();
        return $response;
    } catch ( IOException $e ) {
        $array = array (
            'status' => 0,
            'message' => 'Download error'
        );
        return new JsonResponse ( $array, 400 );
    }
}

Thanks for help !!

CodePudding user response:

  •  Tags:  
  • Related