当前位置: 首页>>代码示例>>PHP>>正文


PHP HttpFoundation\StreamedResponse类代码示例

本文整理汇总了PHP中Symfony\Component\HttpFoundation\StreamedResponse的典型用法代码示例。如果您正苦于以下问题:PHP StreamedResponse类的具体用法?PHP StreamedResponse怎么用?PHP StreamedResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了StreamedResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: exportProCSVAction

 /**
  * @Route("/exportcsvpro", name="export_pro")
  */
 public function exportProCSVAction()
 {
     $now = new \DateTime('now');
     $em = $this->getDoctrine()->getManager();
     $response = new StreamedResponse();
     $response->setCallback(function () use($em) {
         $normalizer = new ObjectNormalizer();
         $count = $em->getRepository('AppBundle:Client')->getCount();
         $total = intval($count[1]);
         $header = array('NOM', 'PRENOM', 'EMAIL', 'SEXE');
         $handle = fopen('php://output', 'r+');
         fputcsv($handle, $header, ";");
         $row = 1;
         while ($total >= 0) {
             $clients = $em->getRepository('AppBundle:Client')->findAllClients(($row - 1) * 2, 2);
             foreach ($clients as $key => $obj) {
                 $clients[$key] = $normalizer->normalize($obj);
             }
             foreach ($clients as $client) {
                 fputcsv($handle, $client, ";");
             }
             $total = $total - 2;
             $row++;
         }
         fclose($handle);
     });
     $response->headers->set('Content-Type', 'application/force-download');
     $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
     return $response;
 }
开发者ID:jethass,项目名称:symfonyImportExport,代码行数:33,代码来源:CsvController.php

示例2: createResponse

 /**
  * Handles response for csv-request.
  *
  * @param ViewHandler $handler
  * @param View $view
  * @param Request $request
  * @param string $format
  *
  * @return Response
  *
  * @throws ObjectNotSupportedException
  */
 public function createResponse(ViewHandler $handler, View $view, Request $request, $format)
 {
     if (!$view->getData() instanceof ListRepresentation) {
         throw new ObjectNotSupportedException($view);
     }
     $viewData = $view->getData();
     $data = new CallbackCollection($viewData->getData(), [$this, 'prepareData']);
     $fileName = sprintf('%s.csv', $viewData->getRel());
     $config = new ExporterConfig();
     $exporter = new Exporter($config);
     $data->rewind();
     if ($row = $data->current()) {
         $config->setColumnHeaders(array_keys($row));
     }
     $config->setDelimiter($this->convertValue($request->get('delimiter', ';'), self::$delimiterMap));
     $config->setNewline($this->convertValue($request->get('newLine', '\\n'), self::$newLineMap));
     $config->setEnclosure($request->get('enclosure', '"'));
     $config->setEscape($request->get('escape', '\\'));
     $response = new StreamedResponse();
     $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $fileName, $fileName);
     $response->headers->set('Content-Type', 'text/csv');
     $response->headers->set('Content-Disposition', $disposition);
     $response->setCallback(function () use($data, $exporter) {
         $exporter->export('php://output', $data);
     });
     $response->send();
     return $response;
 }
开发者ID:sulu,项目名称:sulu,代码行数:40,代码来源:CsvHandler.php

示例3: handle

 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     $uri = $request->path();
     $uri_arr = explode("/", $uri);
     if (in_array($uri, $this->noAuth)) {
         return $next($request);
     } else {
         if ($uri_arr[0] == "stream") {
             $res = $this->permissionForStream($request, $next, $uri_arr[2]);
             if ($res['status'] == "2") {
                 header('Content-Type: text/event-stream');
                 header('Cache-Control: no-cache');
                 $response = new StreamedResponse();
                 $response->setCallback(function () use($res) {
                     $output = json_encode($res);
                     echo "data:" . $output . "\n\n";
                     flush();
                     //sleep(1);
                 });
                 $response->send();
                 exit;
             } else {
                 return $next($request);
             }
         } else {
             $this->_init_($request);
             return $this->permissionToAccess($request, $next);
         }
     }
 }
开发者ID:saran-github,项目名称:repos,代码行数:37,代码来源:AuthenticateRequest.php

示例4: generateExcel

 /**
  * Genera el excel con la planilla de servicios
  * @param type $fechaDesde
  * @param type $fechaHasta
  * @return StreamedResponse
  */
 public function generateExcel($fechaDesde, $fechaHasta)
 {
     $response = new StreamedResponse();
     $response->setCallback(function () use($fechaDesde, $fechaHasta) {
         $fileType = 'Excel2007';
         $fileName = 'template/informeEpidemiologico.xlsx';
         //$objPHPExcel = new PHPExcel();
         $objReader = PHPExcel_IOFactory::createReader($fileType);
         $objPHPExcel = $objReader->load($fileName);
         $objPHPExcel->getProperties()->setCreator("MAB")->setLastModifiedBy("MAB")->setTitle("Informe epidemiológico")->setSubject("Reporte epidemiológico")->setDescription("Informe epidemiológico")->setKeywords("reporte servicio epidemiológico")->setCategory("Reporte excel");
         //Categoria
         // ponemos los datos generales del informe
         $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E3', $fechaDesde)->setCellValue('J3', $fechaHasta);
         $filaServicio = 3;
         $repository = $this->getDoctrine()->getEntityManager()->getRepository('AppBundle:Servicio');
         $query = $repository->createQueryBuilder('s')->where('s.fecha >= :desde')->andwhere('s.fecha < :hasta')->setParameter('desde', $fechaDesde)->setParameter('hasta', $fechaHasta)->orderBy('s.fecha', 'ASC')->getQuery();
         $servicios = $query->getResult();
         foreach ($servicios as $servicio) {
             $this->rellenarServicio($objPHPExcel, $servicio, $filaServicio);
         }
         $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
         if (ob_get_contents()) {
             ob_end_clean();
         }
         $objWriter->save('php://output');
     });
     $response->setStatusCode(200);
     $response->headers->set('Content-Type', 'application/vnd.ms-excel');
     $response->headers->set('Content-Disposition', 'attachment; filename="informeEpidemiologico.xlsx"');
     return $response;
 }
开发者ID:pepesalcedo,项目名称:SEIP,代码行数:37,代码来源:InformeEpidemiologicoController.php

示例5: testGetContent

 public function testGetContent()
 {
     $response = new StreamedResponse(function () {
         echo 'foo';
     });
     $this->assertFalse($response->getContent());
 }
开发者ID:neokensou,项目名称:symfony,代码行数:7,代码来源:StreamedResponseTest.php

示例6: exportAction

 public function exportAction(Request $request, Application $app)
 {
     $exportOptions = $app['exportOptions']['winners'];
     $exportOptionsKeys = array_keys($exportOptions['fields']);
     $exportOptionsValues = array_values($exportOptions['fields']);
     $response = new StreamedResponse();
     $response->setCallback(function () use($app, $exportOptionsKeys, $exportOptionsValues) {
         $handle = fopen('php://output', 'w+');
         fputcsv($handle, $exportOptionsKeys, ';');
         $winners = $app['orm.em']->getRepository('Application\\Entity\\WinnerEntity')->findAll();
         $twig = clone $app['twig'];
         $twig->setLoader(new \Twig_Loader_String());
         foreach ($winners as $winner) {
             $finalExportOptionsValues = array();
             foreach ($exportOptionsValues as $singleValue) {
                 $finalExportOptionsValues[] = $twig->render($singleValue, array('winner' => $winner));
             }
             fputcsv($handle, $finalExportOptionsValues, ';');
         }
         fclose($handle);
     });
     $response->setStatusCode(200);
     $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
     $response->headers->set('Content-Disposition', 'attachment; filename="winners.csv"');
     return $response;
 }
开发者ID:bobalazek,项目名称:contest-o-mat,代码行数:26,代码来源:WinnersController.php

示例7: uploadImageAction

 /**
  * Save uploaded image according to comur_image field configuration
  *
  * @param Request $request
  */
 public function uploadImageAction(Request $request)
 {
     $config = json_decode($request->request->get('config'), true);
     $uploadUrl = $config['uploadConfig']['uploadUrl'];
     $uploadUrl = substr($uploadUrl, -strlen('/')) === '/' ? $uploadUrl : $uploadUrl . '/';
     // We must use a streamed response because the UploadHandler echoes directly
     $response = new StreamedResponse();
     $webDir = $config['uploadConfig']['webDir'];
     $webDir = substr($webDir, -strlen('/')) === '/' ? $webDir : $webDir . '/';
     $filename = sha1(uniqid(mt_rand(), true));
     $thumbsDir = $this->container->getParameter('comur_image.thumbs_dir');
     $thumbSize = $this->container->getParameter('comur_image.media_lib_thumb_size');
     $galleryDir = $this->container->getParameter('comur_image.gallery_dir');
     $gThumbSize = $this->container->getParameter('comur_image.gallery_thumb_size');
     $ext = $request->files->get('image_upload_file')->getClientOriginalExtension();
     //('image_upload_file');
     $completeName = $filename . '.' . $ext;
     $controller = $this;
     $handlerConfig = array('upload_dir' => $uploadUrl, 'param_name' => 'image_upload_file', 'file_name' => $filename, 'upload_url' => $config['uploadConfig']['webDir'], 'min_width' => $config['cropConfig']['minWidth'], 'min_height' => $config['cropConfig']['minHeight'], 'image_versions' => array('thumbnail' => array('upload_dir' => $uploadUrl . $thumbsDir . '/', 'upload_url' => $config['uploadConfig']['webDir'] . '/' . $thumbsDir . '/', 'crop' => true, 'max_width' => $thumbSize, 'max_height' => $thumbSize)));
     $transDomain = $this->container->getParameter('comur_image.translation_domain');
     $errorMessages = array(1 => $this->get('translator')->trans('The uploaded file exceeds the upload_max_filesize directive in php.ini', array(), $transDomain), 2 => $this->get('translator')->trans('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', array(), $transDomain), 3 => $this->get('translator')->trans('The uploaded file was only partially uploaded', array(), $transDomain), 4 => $this->get('translator')->trans('No file was uploaded', array(), $transDomain), 6 => $this->get('translator')->trans('Missing a temporary folder', array(), $transDomain), 7 => $this->get('translator')->trans('Failed to write file to disk', array(), $transDomain), 8 => $this->get('translator')->trans('A PHP extension stopped the file upload', array(), $transDomain), 'post_max_size' => $this->get('translator')->trans('The uploaded file exceeds the post_max_size directive in php.ini', array(), $transDomain), 'max_file_size' => $this->get('translator')->trans('File is too big', array(), $transDomain), 'min_file_size' => $this->get('translator')->trans('File is too small', array(), $transDomain), 'accept_file_types' => $this->get('translator')->trans('Filetype not allowed', array(), $transDomain), 'max_number_of_files' => $this->get('translator')->trans('Maximum number of files exceeded', array(), $transDomain), 'max_width' => $this->get('translator')->trans('Image exceeds maximum width', array(), $transDomain), 'min_width' => $this->get('translator')->trans('Image requires a minimum width (%min%)', array('%min%' => $config['cropConfig']['minWidth']), $transDomain), 'max_height' => $this->get('translator')->trans('Image exceeds maximum height', array(), $transDomain), 'min_height' => $this->get('translator')->trans('Image requires a minimum height (%min%)', array('%min%' => $config['cropConfig']['minHeight']), $transDomain), 'abort' => $this->get('translator')->trans('File upload aborted', array(), $transDomain), 'image_resize' => $this->get('translator')->trans('Failed to resize image', array(), $transDomain));
     $response->setCallback(function () use($handlerConfig, $errorMessages) {
         new UploadHandler($handlerConfig, true, $errorMessages);
     });
     return $response->send();
 }
开发者ID:desmax,项目名称:ComurImageBundle,代码行数:31,代码来源:UploadController.php

示例8: showAction

 /**
  * @Route("/orangegate/media/show/{id}/{format}", name="orangegate_media_show")
  *
  * @throws NotFoundHttpException
  *
  * @param string $id
  * @param string $format
  *
  * @return Response
  */
 public function showAction($id, $format = 'reference')
 {
     $media = $this->getMedia($id);
     if (!$media) {
         throw new NotFoundHttpException(sprintf('unable to find the media with the id : %s', $id));
     }
     $provider = $this->get($media->getProviderName());
     if ($format == 'reference') {
         $file = $provider->getReferenceFile($media);
     } else {
         $file = $provider->getFilesystem()->get($provider->generatePrivateUrl($media, $format));
     }
     $filePath = sprintf('%s/%s', $provider->getFilesystem()->getAdapter()->getDirectory(), $file->getKey());
     if (!$file || !file_exists($filePath)) {
         throw new NotFoundHttpException(sprintf('file not exists : %s', $file->getKey()));
     }
     $response = new StreamedResponse(function () use($file) {
         echo $file->getContent();
     }, Response::HTTP_OK, array('Content-Type' => $media->getContentType(), 'Content-Disposition' => sprintf('inline; filename="%s"', $media->getMetadataValue('filename'))));
     $response->setPrivate();
     $response->headers->addCacheControlDirective('max-age', 0);
     $response->headers->addCacheControlDirective('no-cache', true);
     $response->headers->addCacheControlDirective('no-store', true);
     $response->headers->addCacheControlDirective('must-revalidate', true);
     return $response;
 }
开发者ID:symbio,项目名称:orangegate4-media-bundle,代码行数:36,代码来源:MediaController.php

示例9: call

 /**
  * {@inheritdoc}
  */
 public function call(ActionEvent $event, string $format) : Response
 {
     $controller = $event->getController();
     $this->checkRole($controller);
     $request = $event->getRequest();
     $id = $request->get('id');
     if (is_numeric($id)) {
         if (!$controller->has('knp_snappy.pdf')) {
             throw new \Exception('Have you registered KnpSnappyBundle?');
         }
         $snappy = $controller->get('knp_snappy.pdf');
         $showAction = $controller->get('vardius_crud.action_show');
         $html = $showAction->call($event, 'html')->getContent();
         $response = new Response($snappy->getOutputFromHtml($html, ['margin-bottom' => 3, 'margin-top' => 3, 'margin-left' => 4, 'margin-right' => 14]), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="export.pdf"'));
     } else {
         $type = $request->get('type');
         if ($type === 'pdf') {
             if (!$controller->has('knp_snappy.pdf')) {
                 throw new \Exception('Have you registered KnpSnappyBundle?');
             }
             $snappy = $controller->get('knp_snappy.pdf');
             $listAction = $controller->get('vardius_crud.action_list');
             $html = $listAction->call($event, 'html')->getContent();
             $response = new Response($snappy->getOutputFromHtml($html, ['margin-bottom' => 3, 'margin-top' => 3, 'margin-left' => 4, 'margin-right' => 14]), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="export.pdf"'));
         } else {
             $source = $event->getDataProvider()->getSource();
             if (!$source instanceof EntityRepository) {
                 throw new \Exception('CSV export supports only ORM db driver');
             }
             $queryBuilder = $source->createQueryBuilder('vardius_csv_export');
             $crudEvent = new CrudEvent($source, $controller, $queryBuilder);
             $dispatcher = $controller->get('event_dispatcher');
             $queryBuilder = $dispatcher->dispatch(CrudEvents::CRUD_EXPORT, $crudEvent)->getData();
             $response = new StreamedResponse();
             $response->setCallback(function () use($queryBuilder, $controller) {
                 $handle = fopen('php://output', 'w+');
                 $headers = $controller->getHeaders();
                 if (!empty($headers)) {
                     fputcsv($handle, $headers, ';');
                 }
                 $entityManager = $controller->get('doctrine.orm.entity_manager');
                 $results = $queryBuilder->getQuery()->iterate();
                 while (false !== ($row = $results->next())) {
                     $element = $controller->getRow($row[0]);
                     $entityManager->detach($row[0]);
                     if (count($element)) {
                         fputcsv($handle, $element);
                     }
                 }
                 fclose($handle);
             });
             $response->setStatusCode(200);
             $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
             $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
         }
     }
     return $response;
 }
开发者ID:vardius,项目名称:crud-bundle,代码行数:61,代码来源:ExportAction.php

示例10: stream

 /**
  * Export the workbook.
  *
  * @param null|string $filename
  *
  * @throws \Exception
  * @return mixed|void
  */
 public function stream($filename = null)
 {
     $filename = $this->getFilename($filename);
     $output = $this->getExportable()->getDriver()->getOutputFromHtml($this->convertToHtml($this->getExportable()));
     $response = new StreamedResponse(function () use($output) {
         echo $output;
     }, 200, ['Content-Type' => 'application/pdf', 'Content-Disposition' => 'inline; filename="' . $filename . '.' . $this->getExtension() . '"']);
     return $response->send();
 }
开发者ID:ymnl007,项目名称:Clerk,代码行数:17,代码来源:Writer.php

示例11: setContent

 /**
  * Set the stream response content.
  * @param  StreamedResponse $response The response object.
  * @return StreamedResponse
  */
 public function setContent(StreamedResponse $response)
 {
     $stream = $this->cache->readStream($this->path);
     $response->setCallback(function () use($stream) {
         rewind($stream);
         fpassthru($stream);
         fclose($stream);
     });
     return $response;
 }
开发者ID:awebc,项目名称:web_xbf,代码行数:15,代码来源:ResponseFactory.php

示例12: createStreamedResponse

 /**
  * Create a streamed response containing a file
  *
  * @return \Symfony\Component\HttpFoundation\StreamedResponse
  */
 protected function createStreamedResponse()
 {
     $filename = $this->createFilename();
     $response = new StreamedResponse();
     $attachment = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename);
     $response->headers->set('Content-Type', $this->getContentType());
     $response->headers->set('Content-Disposition', $attachment);
     $response->setCallback($this->quickExportCallback());
     return $response;
 }
开发者ID:a2xchip,项目名称:pim-community-dev,代码行数:15,代码来源:ExportController.php

示例13: fileAction

 /**
  * @Route(
  *     "/image/{node}",
  *     name="claro_image"
  * )
  */
 public function fileAction(ResourceNode $node)
 {
     $image = $this->get('claroline.manager.resource_manager')->getResourceFromNode($node);
     $response = new StreamedResponse();
     $path = $this->container->getParameter('claroline.param.files_directory') . DIRECTORY_SEPARATOR . $image->getHashName();
     $response->setCallBack(function () use($path) {
         readfile($path);
     });
     $response->headers->set('Content-Type', $node->getMimeType());
     return $response->send();
 }
开发者ID:claroline,项目名称:distribution,代码行数:17,代码来源:ImagePlayerController.php

示例14: downloadMatchAction

 public function downloadMatchAction()
 {
     $object = $this->admin->getSubject();
     $matchId = $object->getId();
     if (!$object) {
         throw new NotFoundHttpException(sprintf('Unable to find the object with id : %s', $matchId));
     }
     // On récupère le service qui va envoyer le match
     $response = new StreamedResponse(function () use($matchId) {
         //$downloadMatching = $this->container->get('public_user.exportCsv')->fromMatching($matchId);
         $container = $this->container;
         $em = $container->get('doctrine')->getManager();
         $conn = $em->getConnection();
         // On crée la limite du nombre de donnée recuperés par requetes
         $lim = 10000;
         // On recupere les 10000 premiers resultat
         $query = "SELECT SQL_CALC_FOUND_ROWS md5 FROM matching_details WHERE id_matching = :id LIMIT :lim";
         $sth = $conn->prepare($query);
         $sth->bindValue(':id', $matchId);
         $sth->bindValue(':lim', (int) $lim, \PDO::PARAM_INT);
         $sth->execute();
         $results = $sth->fetchAll();
         // On ouvre le fichier sur lequel on va ecrire
         $handle = fopen('php://output', 'r') or die("Couldn't get handle");
         // On ajout au fichier les données recuperé precedement
         foreach ($results as $row) {
             fputcsv($handle, $row);
         }
         // On recupere le nombre de ligne total
         $sth = $conn->prepare('SELECT FOUND_ROWS()');
         $sth->execute(array($matchId));
         $resultLine = $sth->fetchAll();
         // On recupere le nombre de ligne total
         $nb_line = intval($resultLine[0]["FOUND_ROWS()"]);
         // Si le nombrte de ligne max est superieurs aux nombres de lignes recuperé precedement
         if ($nb_line >= $lim) {
             // on retire du nombre de ligne le nombre d'elements recuperé precedement
             $lineDone = $lim;
             $offset = $lim;
             $this->getData($conn, $matchId, $handle, $nb_line, $lineDone, $lim, $offset);
         } else {
             fclose($handle);
         }
     });
     $response->setStatusCode(200);
     $response->headers->set('Pragma', 'public');
     $response->headers->set('Expires', '0');
     $response->headers->set('Content-Disposition', 'attachment; filename="Export_matching_' . $matchId . '.csv"');
     $response->headers->set('Cache-Control', 'must-revalidate; post-check=0; pre-check=0');
     $response->headers->set('Cache-Control', 'private', false);
     $response->headers->set('Content-Type', 'application/octet-stream');
     $response->headers->set('Content-Transfer-Encoding', 'binary');
     return $response;
 }
开发者ID:StanFrag,项目名称:CCM-Stage,代码行数:54,代码来源:CRUDController.php

示例15: stream

 /**
  * @see StreamingEngineInterface::stream
  */
 public function stream($view, array $parameters = [], StreamedResponse $response = null)
 {
     $callback = function () use($view, $parameters) {
         $this->templating->stream($view, $parameters);
     };
     if (null === $response) {
         return new StreamedResponse($callback);
     }
     $response->setCallback($callback);
     return $response;
 }
开发者ID:fermio,项目名称:traits,代码行数:14,代码来源:TemplatingAware.php


注:本文中的Symfony\Component\HttpFoundation\StreamedResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。