Laravel - File Downloads

2019-04-12 20:35发布

问题:

Hi I'm trying to fix a Laravel download bug I am dealing with. I have the correct route setup, and correct function in the controller. I also am able to confirm that I have access to the file because I created a file using the exact same route and returned it. By doing this I was able to successfully return the contents of the file. However when I try and use a button from the view and call the controller function I get this error:

FileNotFoundException in File.php line 37:
The file "The file "2016-04-04_07-21-50 - Pinging host: 192.168.2.1
2016-04-04_07-21-50 - Host 192.168.2.1 is up!
2016-04-04_07-21-50 - Pinging host: 192.168.2.2
2016-04-04_07-21-53 - Pinging host: 192.168.2.3 ...

Now here is the code that resulted in this error:

show.blade.php

<a class="btn btn-default col-md-12" href="/getDownload/{{ $now }}" role="button">Download Today's Log</a>

HonoursController.php

public function getDownload($id)
    {
      $file = File::get("../resources/logs/$id");
      $headers = array(
           'Content-Type: application/octet-stream',
      );
      #return Response::download($file, $id. '.' .$type, $headers); 
      return response()->download($file, $id.'txt', $headers);
    }

What I have been able to surmise is that I am getting a 500 HTTP error. My inspection does not provide me with any other information however. Any idea what is going on?

回答1:

Try this:

public function getDownload($id)
{
    // $file = File::get("../resources/logs/$id");
    $headers = array(
       'Content-Type: application/octet-stream',
    );
    #return Response::download($file, $id. '.' .$type, $headers); 
    return response()->download("../resources/logs/$id", $id.'txt', $headers);
}

From the docs:

The download method may be used to generate a response that forces the user's browser to download the file at the given path.

return response()->download($pathToFile, $name, $headers);

https://laravel.com/docs/5.1/responses#basic-responses



回答2:

The first argument of the download method should be a path to the file, not the file itself.

The download method may be used to generate a response that forces the user's browser to download the file at the given path. ...

Source: https://laravel.com/docs/5.2/responses#file-downloads