15. Các loại response khác Download file (Other response types)(ok)
https://viblo.asia/p/tap-17-response-laravel-aWj534RGK6m
Method download
thường được sử dụng để tạo một response bắt buộc người dùng download một file tại đường dẫn nhất định.
return response()->download($pahtFile, $nameFile, $headers);
Method này chấp nhận tham số thứ hai để thay đổi tên file khi người dùng download. Ngoài ra ta có thể truyền thêm mảng cấu hình các header thông qua tham số thứ ba.
Lưu ý: Mặc định method
download
sẽ được gán base pathpublic
cho đường dẫn fle donwload.
Chẳng hạn bây giờ mình muốn download file resources/views/welcome.blade.php
mặc định của Laravel. Các bạn thử đăng ký route sau giống mình:
Route::get('/download', function() {
return response()->download('../resources/views/welcome.blade.php');
});
Bây giờ thử chạy route đó xem, ta sẽ thu được kết quả như thế này:
Nếu bạn muốn một cái tên khác khi download, có thể thêm tham số thứ hai như sau:
Route::get('/download', function() {
return response()->download('../resources/views/welcome.blade.php', 'other_name.php');
});
Kết qua trên thấy được blade view welcome.blade.php
đã được rename thành other_name.php
rồi đấy.
Như đã nói ở trên, bạn có thể truyền mảng header tại tham số thứ ba của method download
.
return response()->download($pathFile, $nameFile, $headers);
Bạn có thể khai báo các header theo dạng cấu trúc mảng.
$headers = [
'X-Header-One' => 'Header value 1',
'X-Header-Two' => 'Header value 2',
// ...
];
Lưu ý: Nếu muốn thêm tham số header mà không thay đổi tên file donwload thì tại tham số thứ hai khai báo giá trị
null
.return response()->download($pathFile, null, $headers);
Ngoài ra bạn có thể xóa file ngay sau khi người dùng download bằng cách sử dụng method deleteFileAfterSend
.
return response()->download($pathFile, $nameFile, $headers)->deleteFileAfterSend();
Last updated
Was this helpful?