16. Các loại response khác Streamed download (Other response types)(ok)

https://viblo.asia/p/tap-17-response-laravel-aWj534RGK6m

Nếu bạn muốn người dùng download một nội dung nào đó mà chưa được ghi vào file nào trong hệ thống của bạn thì có thể dùng method streamDownload.

Phương thức streamDownload sẽ nhận ba tham số:

  • Tham số thứ nhất là một Closure có nhiệm vụ thực hiện xử lý để echo nội dung cho file.

  • Tham số thứ hai là tên file download.

  • Tham số thứ ba (tùy chọn) là các thiết lập header.

return response()->streamDownload(Closure, $nameFile, $headers);

Bạn có thể tạo route này để test:

Route::get('/stream', function() {
    return response()->streamDownload(function() {
        echo 'Lê Chí Huy';
    }, 'users.txt');
});

Các bạn cứ chạy xem kết quả thì sẽ hình dung ra ngay.

Nội dung của file users.txt sau khi tải về sẽ là:

Lê Chí Huy

Lưu ý: Bắt buộc phải dùng lệnh echo thì nội dung mới ghi được trên file download. Nội dung của file chỉ được là dạng text.

Last updated