Problem with downloading PDF file with laravel

1

I have a system for downloading PDF files, what is happening and what I try to download, and it simply does not download. I have seen in the chromo inspector and no error.

Controller

class DownloadController extends Controller{

    public function getDownload (){

      $filename = 'certificacoes/teste.pdf';
      $path = storage_path($filename);

      return Response::make(file_get_contents($path), 200, [
          'Content-Type' => 'application/pdf',
          'Content-Disposition' => 'inline; filename="'.$filename.'"'
      ]);
    }
}

Jquery

$(function(){
  $("body").on('click', '#download_link', function(e) {
    e.preventDefault();
    var creditos = {{$creditos}}

    if(creditos == 0){
      sweetAlert("Erro...", 'Não tem créditos disponiveis. Efectue upload de uma certificação', "error");
    }else{

      $.ajax({
          type: 'POST',
          url: '/download',
          headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
          //data: formData
      }).done(function(response) {

      }).fail(function(data) {
          sweetAlert("Erro...", 'Ocorreu um erro ao efectuar o download. Por favor tente novamente!', "error");
      });
    }
  });
});

    
asked by anonymous 29.10.2017 / 23:37

1 answer

0

Using Ajax to download the files is not the best way. By security measure you can not save a file on the user's computer using javascript. Reference: link .

  

JavaScript

     

You can not automatically write to the hard disk.

What you can do is redirect the user to the download URL.

window.location = 'URL_DOWNLOAD';

If you want to improve how your controller creates the download response , according to the Laravel documentation link , you can send a download response in two ways:

That way when the URL is accessed the browser will start a download

return response()->download($path, $name, $headers);
// OU
return Response::download($path, $name, $headers);

Using this form when accessing the URL the browser will try to open the file instead of downloading directly

return response()->file($path);
//OU
return Response::file($path);
    
30.10.2017 / 12:55