Anonymous
Как принудительно загрузить с помощью функции пересылки Symfony 6?
Сообщение
Anonymous » 18 сен 2024, 00:10
Проблема заключается в отправке данных с одного контроллера на другой с помощью функции пересылки Symfony.
Эта функция объясняется здесь
В моем первом контроллере я выполняю ограниченный запрос по датам, указанным оператором.
Код: Выделить всё
#[Route('/admin/fuente/exportar0/', name: 'app_exportar0_fuente', methods: ['GET', 'POST'])]
public function exportar0(Request $request, FuenteRepository $fuenteRepository, CSVResponse $CSVResponse): Response
{
$defaultData = [];
$form = $this->createFormBuilder($defaultData, ['method' => Request::METHOD_GET])
->add('fecha_desde', DateType::class, array(
'label' => 'Fecha desde?: ',
'input'=>'string', 'required' => true,
'widget' => 'single_text',
'attr' => array('style' => 'width: 120px'),
))
->add('fecha_hasta', DateType::class, array(
'label' => 'Fecha hasta?: ',
'input'=>'string', 'required' => true,
'widget' => 'single_text',
'attr' => array('style' => 'width: 120px'),
))
->add('save', SubmitType::class, ['label' => 'Buscar'])
->getForm();
$form->handleRequest($request);
if($form->isSubmitted()&&$form->isValid()){
// datafecha is an array with "fecha_desde", and "fecha_hasta" keys
$datafechas = $form->getData();
$noticias = $fuenteRepository->findTodosCSV($datafechas);
$response = $this->forward('App\Controller\FuenteController::csvAction', [
'noticias' => $noticias
]);
return $response;
}
return $this->render('fuente/entrefechas.html.twig', array(
'form' => $form->createView() ));
}
Во втором контроллере я использую результат запроса предыдущего контроллера для создания CSV-файла и загрузки его.
Код: Выделить всё
#[Route('/admin/fuente/csv/', name: 'app_csv_fuente', methods: ['GET', 'POST'])]
public function csvAction(array $noticias ): Response
{
$data=array();
$data[0]= array("Id","Diario","Link", "Palabras","Título","Contenido","Fecha","Mes", "Año",
"Protagonista", "Dinámica Conflictual", "Sector", "Sub sector", "Departamento","Pertenencia",
"Agrupación", "Agregación", "Antagonista", "Actor Estatal","Nivel de Gobierno", "Participación",
"Protagonista", "Respuesta Patronal 1","Respuesta Patronal 2", "Respuesta Estado 1", "Respuesta Estado 2",
"Demanda 1 nombre", "Demanda 1 principal","Demanda 2 nombre","Demanda 2 principal",
"Demanda 3 nombre", "Demanda 3 principal", "Actor emergente",
"Formato","Formato 2","Formato 3",
);
$i=1;
foreach ($noticias as $noticia) {
$data[$i]= array(
$noticia['id'],
$noticia['diario'],
$noticia['link'],
$noticia['palabras'],
$noticia['titulo'],
$noticia['contenido'],
$noticia['fecha']->format('d-m-Y'),
$noticia['fecha']->format('F'),
$noticia['fecha']->format('Y'),
$noticia['protagonista_name'],
$noticia['actividad_name'],
$noticia['sector_name'],
$noticia['subsector_name'],
$noticia['Departamento'],
$noticia['Pertenencia'],
$noticia['Agrupacion'],
$noticia['Agregacion'],
$noticia['Antagonista'],
$noticia['Actorestatal'],
$noticia['Nivelgobierno'],
$noticia['Participacion'],
$noticia['protagonista_name'],
$noticia['respuestapatronal_name'],
$noticia['respuestapatronal1_name'],
$noticia['respuestaestado_name'],
$noticia['respuestaestado1_name'],
$noticia['demanda1_name'],
$noticia['principal1_name'],
$noticia['demanda2_name'],
$noticia['principal2_name'],
$noticia['demanda3_name'],
$noticia['principal3_name'],
$noticia['Actoremergente'],
$noticia['protesta_name'],
$noticia['protesta_name2'],
$noticia['protesta_name3'] ,
);
$i++;
}
$fp = fopen('php://memory','w', "w");
foreach($data as $fields){
fputcsv($fp, $fields, ';');
}
rewind($fp);
$response = new Response(stream_get_contents($fp));
fclose($fp);
$response->headers->set('Content-Type', 'text/csv; charset=UTF-8');
$response->headers->set('Content-Encoding', 'UTF-8');
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-Disposition', 'attachment; filename="noticias.csv"');
$response->sendHeaders();
return $response;
}
Проблема в том, что загрузка не работает, но файл csv создается!
Когда я применяю эту функцию к загрузке, этого не происходит, но файл где-то генерируется в памяти или пространстве сервера. Откуда мне знать?
Если я поищу раздел Ajax на нижней панели инструментов, я увижу список сгенерированных, но не загруженных файлов.
Если мы нажмем на некоторые из этих ссылок на панели функций, загрузка осуществляется там.
Задача состоит в том, как добиться прямой загрузки
Подробнее здесь:
https://stackoverflow.com/questions/789 ... d-function
1726607430
Anonymous
Проблема заключается в отправке данных с одного контроллера на другой с помощью функции пересылки Symfony. Эта функция объясняется здесь В моем первом контроллере я выполняю ограниченный запрос по датам, указанным оператором. [code]#[Route('/admin/fuente/exportar0/', name: 'app_exportar0_fuente', methods: ['GET', 'POST'])] public function exportar0(Request $request, FuenteRepository $fuenteRepository, CSVResponse $CSVResponse): Response { $defaultData = []; $form = $this->createFormBuilder($defaultData, ['method' => Request::METHOD_GET]) ->add('fecha_desde', DateType::class, array( 'label' => 'Fecha desde?: ', 'input'=>'string', 'required' => true, 'widget' => 'single_text', 'attr' => array('style' => 'width: 120px'), )) ->add('fecha_hasta', DateType::class, array( 'label' => 'Fecha hasta?: ', 'input'=>'string', 'required' => true, 'widget' => 'single_text', 'attr' => array('style' => 'width: 120px'), )) ->add('save', SubmitType::class, ['label' => 'Buscar']) ->getForm(); $form->handleRequest($request); if($form->isSubmitted()&&$form->isValid()){ // datafecha is an array with "fecha_desde", and "fecha_hasta" keys $datafechas = $form->getData(); $noticias = $fuenteRepository->findTodosCSV($datafechas); $response = $this->forward('App\Controller\FuenteController::csvAction', [ 'noticias' => $noticias ]); return $response; } return $this->render('fuente/entrefechas.html.twig', array( 'form' => $form->createView() )); } [/code] Во втором контроллере я использую результат запроса предыдущего контроллера для создания CSV-файла и загрузки его. [code] #[Route('/admin/fuente/csv/', name: 'app_csv_fuente', methods: ['GET', 'POST'])] public function csvAction(array $noticias ): Response { $data=array(); $data[0]= array("Id","Diario","Link", "Palabras","Título","Contenido","Fecha","Mes", "Año", "Protagonista", "Dinámica Conflictual", "Sector", "Sub sector", "Departamento","Pertenencia", "Agrupación", "Agregación", "Antagonista", "Actor Estatal","Nivel de Gobierno", "Participación", "Protagonista", "Respuesta Patronal 1","Respuesta Patronal 2", "Respuesta Estado 1", "Respuesta Estado 2", "Demanda 1 nombre", "Demanda 1 principal","Demanda 2 nombre","Demanda 2 principal", "Demanda 3 nombre", "Demanda 3 principal", "Actor emergente", "Formato","Formato 2","Formato 3", ); $i=1; foreach ($noticias as $noticia) { $data[$i]= array( $noticia['id'], $noticia['diario'], $noticia['link'], $noticia['palabras'], $noticia['titulo'], $noticia['contenido'], $noticia['fecha']->format('d-m-Y'), $noticia['fecha']->format('F'), $noticia['fecha']->format('Y'), $noticia['protagonista_name'], $noticia['actividad_name'], $noticia['sector_name'], $noticia['subsector_name'], $noticia['Departamento'], $noticia['Pertenencia'], $noticia['Agrupacion'], $noticia['Agregacion'], $noticia['Antagonista'], $noticia['Actorestatal'], $noticia['Nivelgobierno'], $noticia['Participacion'], $noticia['protagonista_name'], $noticia['respuestapatronal_name'], $noticia['respuestapatronal1_name'], $noticia['respuestaestado_name'], $noticia['respuestaestado1_name'], $noticia['demanda1_name'], $noticia['principal1_name'], $noticia['demanda2_name'], $noticia['principal2_name'], $noticia['demanda3_name'], $noticia['principal3_name'], $noticia['Actoremergente'], $noticia['protesta_name'], $noticia['protesta_name2'], $noticia['protesta_name3'] , ); $i++; } $fp = fopen('php://memory','w', "w"); foreach($data as $fields){ fputcsv($fp, $fields, ';'); } rewind($fp); $response = new Response(stream_get_contents($fp)); fclose($fp); $response->headers->set('Content-Type', 'text/csv; charset=UTF-8'); $response->headers->set('Content-Encoding', 'UTF-8'); $response->headers->set('Cache-Control', 'private'); $response->headers->set('Content-Disposition', 'attachment; filename="noticias.csv"'); $response->sendHeaders(); return $response; } [/code] Проблема в том, что загрузка не работает, но файл csv создается! Когда я применяю эту функцию к загрузке, этого не происходит, но файл где-то генерируется в памяти или пространстве сервера. Откуда мне знать? Если я поищу раздел Ajax на нижней панели инструментов, я увижу список сгенерированных, но не загруженных файлов. Если мы нажмем на некоторые из этих ссылок на панели функций, загрузка осуществляется там. Задача состоит в том, как добиться прямой загрузки Подробнее здесь: [url]https://stackoverflow.com/questions/78995723/how-to-force-a-download-using-symfony-6s-forward-function[/url]