做一個文字生成圖片的功能,客戶端需要接收是二進制圖片,webman如何返回二進制圖片?
http://wtbis.cn/doc/webman/response.html
返回文件流
<?php
namespace app\controller;
use support\Request;
class FooController
{
public function hello(Request $request)
{
return response()->file(public_path() . '/favicon.ico');
}
}
webman支持發(fā)送超大文件
對于大文件(超過2M),webman不會將整個文件一次性讀入內存,而是在合適的時機分段讀取文件并發(fā)送
webman會根據客戶端接收速度來優(yōu)化文件讀取發(fā)送速度,保證最快速發(fā)送文件的同時將內存占用減少到最低
數據發(fā)送是非阻塞的,不會影響其它請求處理
file方法會自動添加if-modified-since頭并在下一個請求時檢測if-modified-since頭,如果文件未修改則直接返回304以便節(jié)省帶寬
發(fā)送的文件會自動使用合適的Content-Type頭發(fā)送給瀏覽器
如果文件不存在,會自動轉為404響應
下載文件
<?php
namespace app\controller;
use support\Request;
class FooController
{
public function hello(Request $request)
{
return response()->download(public_path() . '/favicon.ico', '可選的文件名.ico');
}
}
download方法與file方法的區(qū)別是download方法一般用于下載并保存文件,并且可以設置下載的文件名。download方法不會檢查if-modified-since頭。其它與file方法行為一致。
獲取輸出
有些類庫是將文件內容直接打印到標準輸出的,也就是數據會打印在命令行終端里,并不會發(fā)送給瀏覽器,這時候我們需要通過ob_start(); ob_get_clean(); 將數據捕獲到一個變量中,再將數據發(fā)送給瀏覽器,例如:
<?php
namespace app\controller;
use support\Request;
class ImageController
{
public function get(Request $request)
{
// 創(chuàng)建圖像
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// 開始獲取輸出
ob_start();
// 輸出圖像
imagejpeg($im);
// 獲得圖像內容
$image = ob_get_clean();
// 發(fā)送圖像
return response($image)->header('Content-Type', 'image/jpeg');
}
}