This article focuses on introducing the example code of Laravel to implement the file download function. Friends who need it can refer to it
The last LTS (long-term support) version of Laravel is Laravel 5.1, which was released in June 2015. According to the agreement on the LTS version, the two-year bug fix support will end in the middle of this year, so an LTS successor version will inevitably be released in the middle of this year, which is Laravel 5.5. This article focuses on introducing the implementation method of Laravel's file download function. Please refer to this article.
download method can be used to generate a response that forces the user's browser to download a file with a specified path. The download method accepts the file name as the second parameter of the method. This name is the file name that the user sees when downloading the file. Finally, you can pass an array containing HTTP header information as the third parameter to the method:
return response()->download($pathToFile); return response()->download($pathToFile, $name, $headers);
The following is the file download function I use in my project.
public function downloadfile($filename) { $file = public_path().'/test.xls'; return response()->download($file,$filename.'.xls'); }
However, the progress was not very smooth at the beginning. Why did the file download function that comes with laravel fail? The error message is as follows:
FatalErrorException in HandleCors.php line 18: Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header()
The general meaning is that the header() method has not been defined. After various explorations, we found a solution. We can redefine the header and add the following method to the handle method of CorsMiddleware:
class CorsMiddleware { public function handle($request, Closure $next) { $response = $next($request); $response->headers->set('Access-Control-Allow-Origin' , '*'); $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE'); $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application'); return $response; } }
Finally, after redefining the header, we used the download function and found that we could access it normally.
Summarize
The above is the detailed content of Sample code for implementing file download function using Laravel framework. For more information, please follow other related articles on the PHP Chinese website!