We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Action in the controller with readfile, where the name is passed by POST method through ajax call.

This is killing me ... dumbest thing but I dont see the point. Summarizing I want an anchor run a controller action which is basically a readfile (typical save as... window). This I managed but what I do not get is run it with an ajax POST method, passing the file name in the call (not in the url). Calling, call the action, but not with variable ... lets see some code:


public function descargarimagenAction(){

//Problem in the call, POST arrived here!

$nombre = $this->request->getPost("nombre");

$extension = "jpg";

$this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER);

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

header('Content-Description: File Transfer');

header('Content-type: image/' . $extension);

header('Content-Disposition: attachment; filename="'.$nombre.'"');

readfile("img/".$nombre);

die();

}

And the html:


<a class="btn btn-primary" href="notificaciones/descargarimagen" onclick="$.post(href,

{nombre: 'imagendeprueba.jpg'},function(data){alert('done')});return false">

The alert activated, and the POST request to the function too, but the readfile or doesn't work or doesn't answers to the view. Any ideas? The thing is that by href = "notifications / descargarimagen / imagendeprueba.jpg" I can download, everything perfect. (instead of getPost use a simple variable parameter in the action BTW).



51.2k

This is not related to Phalcon. If you want to achieve this, please check the answers from here https://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post

You were right, I managed it with a form with POST.

I think there could be a huge security issue by allowing to show any file passed by $_POST. Consider filter path characters like . (dot) \ and / in $this->request->getPost("nombre").