[0020]routesを利用して任意のURLにて画像ファイルを表示
■画像ファイル表示
この例のLalavelフレームワークのバージョンは5.5です。
任意のURLにて画像ファイルを表示するため、ルーティングの設定をroutes/web.phpに追加します。
web.php
//画像表示
Route::get('photo/{target}/{id}', 'PhotoController@show');
次に画像ファイルを配置する・しているパスを呼び出し時に利用するため、config/app.phpに画像パスを追加します。
app.php
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
],
// アップロードパス
'upload_path'=>'/var/www/vhost/xxx/public/uploads/',
次にコントローラ(Controller)を追加します。ルーティングの設定で指定した通り、名前を「PhotoController」にします。
PhotoController.php
<?php
namespace App\Http\Controllers;
use App\RoundTripTmp;
use Illuminate\Http\Request;
use Config;
class PhotoController extends Controller
{
public function show($target,$id)
{
$file = '';
switch ($target) {
case 'round_trip':
$db = RoundTripTmp::find($id);
$file_path = \Config::get('app.upload_path').$target.'/'.$id."/".$db->photo_nm;
if (file_exists($file_path)) {
$file = $file_path;
}
break;
case 'city':
$db = City::find($id);
$file_path = \Config::get('app.upload_path').$target.'/'.$id."/".$db->photo_nm;
if (file_exists($file_path)) {
$file = $file_path;
}
break;
}
if ($file !== '') {
$response = \Response::make(\File::get($file));
$response->header('Content-Type', mime_content_type($file));
$response->header('Pragma', 'no-cache');
return $response;
} else {
// no image
$file = public_path().'/images/noimage.jpeg';
$response = \Response::make(\File::get($file));
$response->header('Content-Type', mime_content_type($file));
}
return $response;
}
}
$targetがround_tripの場合は、round_tripsテーブルから。cityの場合は、citysテーブルから画像名を取得し、表示します。
画像がない場合は、noimage.jpegで画像無しの画像を表示します。
https://www.xxx.com/photo/round_trip/1 や https://www.xxx.com/photo/city/4 などで表示できるようになります。
必要なものに合わせてroutesのパラメータやControllerのプログラムを変更することで様々な画像表示を共通化できます。