PHP-返回带有可下载网址的响应

时间:2019-05-07 13:27:39

标签: php symfony download response symfony-3.4

我试图花费数小时来弄清楚如何返回我的csv文件通过URL作为响应。 CSV文件在那里,URL已匹配,但我不知道如何在响应中返回可下载的URL。

  $rootDir = $this->container->get('kernel')->getRootDir();
  $dir = $rootDir . '/../web/uploads/news/';

  /// - rest of the code that is not relevant and generates my csv $fileName

  $fp = fopen($fileName, 'w');

在这一部分中,我尝试设置我的响应标头和可下载的网址,但没有成功:

 $baseurl = $request->getScheme() . '://' . $request->getHttpHost()
. $request->getBasePath() . $dir . $fileName;


    // Set response
    $response = new BinaryFileResponse($dir .DIRECTORY_SEPARATOR. $fileName);

    // Set headers
    $d = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT,
         $fileName
    );
    $response->headers->set('Content-Disposition', $d);

    return $this->success();

1 个答案:

答案 0 :(得分:0)

    $response = new BinaryFileResponse($pathToFile);
    $response->setContentDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT,
        'filenameThatWillBeDownloaded.yourextension'
    );

    return $response;

别忘了导入类

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;