Home > Article > PHP Framework > Laravel download function cannot be used in Chinese
When developing using Laravel, we may encounter the problem that the download function cannot correctly handle Chinese file names. This problem is mainly caused by the inclusion of Chinese characters in the file name. To solve this problem we need to URL encode the filename.
In PHP, you can use the urlencode()
function to encode file names. However, in Laravel we can use the built-in Str::slug()
method to accomplish this task.
Str::slug()
The method can convert a string into URL-friendly "slug" format. However, we can choose not to pass in the second parameter to retain the original characters and only perform URL encoding.
The following is a sample code:
public function downloadFile($filename) { $fullPath = storage_path('app/download/' . $filename); $headers = [ 'Content-Type' => 'application/octet-stream', ]; $escapedFilename = Str::slug($filename, ''); return response()->download($fullPath, $escapedFilename, $headers); }
In the above code, we use the Str::slug()
method to encode the file name and The encoded string is passed as the second parameter to the download()
method.
In this way, we can ensure that Laravel can correctly handle file names containing Chinese characters when processing downloaded files.
The above is the detailed content of Laravel download function cannot be used in Chinese. For more information, please follow other related articles on the PHP Chinese website!