Home > Backend Development > PHP Tutorial > How to Download Files in Laravel Using Response::download?

How to Download Files in Laravel Using Response::download?

Mary-Kate Olsen
Release: 2024-11-04 15:20:02
Original
454 people have browsed it

How to Download Files in Laravel Using Response::download?

Downloading Files in Laravel Using Response::download

In Laravel, the Response::download method allows users to download files from the server. Here's a solution to the issues faced when implementing this functionality:

1. File Path Issue:

The error "The file...not exist" indicates an incorrect file path. To resolve this, use the public_path() helper to specify the full physical path to the file:

$file= public_path(). "/download/info.pdf";
Copy after login

2. Preventing Page Navigation:

To avoid navigating to another view or route, use an Ajax request to handle the file download. Here's how:

ViewController:

<button class="btn btn-large pull-right" data-href="/download" id="downloadBtn">
    <i class="icon-download-alt"></i> Download Brochure
</button>
Copy after login

JavaScript:

$(document).ready(function() {
    $('#downloadBtn').click(function() {
        $.ajax({
            url: $(this).data('href'),
            success: function() {
                alert('File downloaded successfully!');
            },
            error: function() {
                alert('Error downloading file!');
            }
        });
    });
});
Copy after login

Controller:

public function getDownload()
{
    // Same code as before, but now it returns a JSON response
    return response()->json([
        'success' => true,
        'message' => 'File downloaded successfully!'
    ]);
}
Copy after login

Update for Laravel v5.0 :

As pointed out in the solution, you can use the response() method in Laravel v5.0 instead of the Response facade. The header structure is also slightly different, as shown below:

$headers = [
    'Content-Type' => 'application/pdf',
];

return response()->download($file, 'filename.pdf', $headers);
Copy after login

The above is the detailed content of How to Download Files in Laravel Using Response::download?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template