Problem with download PDF file with Laravel

Asked

Viewed 768 times

2

I have a system to download PDF files, which is happening and I try to download, and it just doesn’t download. I’ve seen in the by the inspector of the Chromo and there is no mistake.

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");
      });
    }
  });
});

inserir a descrição da imagem aqui

  • Have you tried accessing URL straight through Ajax ?

  • Some suggestions and cases that can cause this... 1. Check the permissions of folders and files. 2. Routes are correct, calling the function of the Controller and sending the answer? Make a console.log on ajax and returns a simple answer to see if everything is right in this process. 3. Your Response is being added at the beginning of the file? 4. Have you tried using a library to do this in a simpler way? Index o [DOMPDF][1] [1]: https://github.com/barryvdh/laravel-dompdf

1 answer

1

Using Ajax to download files is not the best way. By security measure you cannot save a file on the user’s computer using javascript. Reference: https://developer.mozilla.org/pt-PT/docs/Web/JavaScript/Guia/Introdu%C3%A7%C3%A3o_ao_JavaScript.

Javascript

Cannot automatically write to hard drive.

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

window.location = 'URL_DOWNLOAD';

If you want to improve the way your controller creates the download response, according to Laravel’s documentation link, you can send a download reply 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 way 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.