简体   繁体   中英

Laravel - Force download with response()->download($fileLocation) not working

I'm creating a downloads functionality with Laravel. When the user clicks on the 'download' button, I initiate an ajax call to the controller which looks like this -

public function download(Resource $resource) {
    // Force download of the file
    $file_to_download   = 'https://data.domain.com/downloads/' . $resource->file_name;
    $temp_file_location =   public_path('/tmp_files/' . $resource->file_name);
    copy($file_to_download, $temp_file_location);
    return response()->download($temp_file_location)->deleteFileAfterSend(true);
}

Chrome's inspector shows that the response gets populated with the contents of the file, but it won't trigger the actual download.

I've been trying to find an answer, but have had no success so far. Would really appreciate your help.

Thank you for your time.

You cannot download a file from an Ajax request because Javascript is unable to save files to your filesystem out of security concerns.

There are a few good packages out there like Jquery File Download

Or you can use a traditional GET request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM