BinaryFileResponse example

return new JsonResponse($json$status$headers, true);
        }

        return new JsonResponse($data$status$headers);
    }

    /** * Returns a BinaryFileResponse object with original or customized file name and disposition header. */
    protected function file(\SplFileInfo|string $file, string $fileName = null, string $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
    {
        $response = new BinaryFileResponse($file);
        $response->setContentDisposition($disposition$fileName ?? $response->getFile()->getFilename());

        return $response;
    }

    /** * Adds a flash message to the current session for type. * * @throws \LogicException */
    protected function addFlash(string $type, mixed $message): void
    {

  public function deliver(Request $request, string $file_name) {
    $uri = 'assets://' . $this->assetType . '/' . $file_name;

    // Check to see whether a file matching the $uri already exists, this can     // happen if it was created while this request was in progress.     if (file_exists($uri)) {
      return new BinaryFileResponse($uri, 200, [
        'Cache-control' => static::CACHE_CONTROL,
        // @todo: remove the explicit setting of Content-Type once this is         // fixed in https://www.drupal.org/project/drupal/issues/3172550.         'Content-Type' => $this->contentType,
      ]);
    }

    // First validate that the request is valid enough to produce an asset group     // aggregate. The theme must be passed as a query parameter, since assets     // always depend on the current theme.     if (!$request->query->has('theme')) {
      
foreach ($headers as $result) {
        if ($result == -1) {
          throw new AccessDeniedHttpException();
        }
      }

      if (count($headers)) {
        // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()         // sets response as not cacheable if the Cache-Control header is not         // already modified. We pass in FALSE for non-private schemes for the         // $public parameter to make sure we don't change the headers.         return new BinaryFileResponse($uri, 200, $headers$scheme !== 'private');
      }

      throw new AccessDeniedHttpException();
    }

    throw new NotFoundHttpException();
  }

}
$psrResponse = self::buildHttpMessageFactory()->createResponse($response);

        $this->assertSame("Line 1\nLine 2\n", $psrResponse->getBody()->__toString());
    }

    public function testCreateResponseFromBinaryFile()
    {
        $path = tempnam($this->tmpDir, uniqid());
        file_put_contents($path, 'Binary');

        $response = new BinaryFileResponse($path);

        $psrResponse = self::buildHttpMessageFactory()->createResponse($response);

        $this->assertSame('Binary', $psrResponse->getBody()->__toString());
    }

    public function testCreateResponseFromBinaryFileWithRange()
    {
        $path = tempnam($this->tmpDir, uniqid());
        file_put_contents($path, 'Binary');

        
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\Stream;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Tests\File\FakeFile;

class BinaryFileResponseTest extends ResponseTestCase
{
    public function testConstruction()
    {
        $file = __DIR__.'/../README.md';
        $response = new BinaryFileResponse($file, 404, ['X-Header' => 'Foo'], true, null, true, true);
        $this->assertEquals(404, $response->getStatusCode());
        $this->assertEquals('Foo', $response->headers->get('X-Header'));
        $this->assertTrue($response->headers->has('ETag'));
        $this->assertTrue($response->headers->has('Last-Modified'));
        $this->assertFalse($response->headers->has('Content-Disposition'));

        $response = new BinaryFileResponse($file, 404, [], true, ResponseHeaderBag::DISPOSITION_INLINE);
        $this->assertEquals(404, $response->getStatusCode());
        $this->assertFalse($response->headers->has('ETag'));
        $this->assertEquals('inline; filename=README.md', $response->headers->get('Content-Disposition'));
    }

    
$header->setLanguageName($language_name);

      $writer = new PoStreamWriter();
      $writer->setURI($uri);
      $writer->setHeader($header);

      $writer->open();
      $writer->writeItem($item);
      $writer->writeItems($reader);
      $writer->close();

      $response = new BinaryFileResponse($uri);
      $response->setContentDisposition('attachment', $filename);
      $form_state->setResponse($response);
    }
    else {
      $this->messenger()->addStatus($this->t('Nothing to export.'));
    }
  }

}
if ($success) {
      $image = $this->imageFactory->get($derivative_uri);
      $uri = $image->getSource();
      $headers += [
        'Content-Type' => $image->getMimeType(),
        'Content-Length' => $image->getFileSize(),
      ];
      // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()       // sets response as not cacheable if the Cache-Control header is not       // already modified. When $is_public is TRUE, the following sets the       // Cache-Control header to "public".       return new BinaryFileResponse($uri, 200, $headers$is_public);
    }
    else {
      $this->logger->notice('Unable to generate the derived image located at %path.', ['%path' => $derivative_uri]);
      return new Response($this->t('Error generating image.'), 500);
    }
  }

  /** * Checks whether the provided source image exists. * * @param string $image_uri * The URI for the source image. * @param bool $token_is_valid * Whether a valid image token was supplied. * * @return bool * Whether the source image exists. */
$path_matcher->isFrontPage()->shouldNotBeCalled();

    $subscriber = new ActiveLinkResponseFilter(
      $session,
      $current_path_stack,
      $path_matcher->reveal(),
      $language_manager
    );

    // Test BinaryFileResponse is ignored. Calling setContent() would throw a     // logic exception.     $response = new BinaryFileResponse(__FILE__, 200, ['Content-Type' => 'text/html']);
    $subscriber->onResponse(new ResponseEvent(
      $this->prophesize(KernelInterface::class)->reveal(),
      $request_stack->getCurrentRequest(),
      HttpKernelInterface::MAIN_REQUEST,
      $response
    ));

    // Test StreamedResponse is ignored. Calling setContent() would throw a     // logic exception.     $response = new StreamedResponse(function D) {
      echo 'Success!';
    },
return $response;
  }

  /** * Returns an example thumbnail file without an extension. * * @return \Symfony\Component\HttpFoundation\BinaryFileResponse * The response. */
  public function getThumbnailWithNoExtension() {
    $response = new BinaryFileResponse('core/misc/druplicon.png');
    $response->headers->set('Content-Type', 'image/png');
    return $response;
  }

  /** * Maps an asset URL to a local fixture representing its oEmbed resource. * * @param string $asset_url * The asset URL. * @param string $resource_path * The path of the oEmbed resource representing the asset. */
      // least we'll get an empty xml response instead of a bunch of Drupal page       // output.       $availability_scenario = '#broken#';
    }

    $file = __DIR__ . "/../../../../fixtures/release-history/$project_name.$availability_scenario.xml";
    $headers = ['Content-Type' => 'text/xml; charset=utf-8'];
    if (!is_file($file)) {
      // Return an empty response.       return new Response('', 200, $headers);
    }
    return new BinaryFileResponse($file, 200, $headers);
  }

}
Home | Imprint | This part of the site doesn't use cookies.