首页 > 解决方案 > 通过路由访问存储在公共目录中的图像

问题描述

我想通过路由访问存储在 laravel 中公用文件夹中的图像,以防万一搜索图像是否存在于我的公用文件夹中,到目前为止,这是我的代码:

api.php

Route::group(['prefix' => 'images', 'middleware' => 'cors'], function () {
Route::get('itemsImages/{imagename}','ManagerController@itemImage');
});

管理控制器.php

public function itemImage($imagename)
{
    // Check if file exists in storage directory
    $file_path = public_path() .'/images/itemsImages/'.$imagename;
    if (file_exists($file_path))
        return Response::download($file_path);
    else
        dd($file_path);
        //does not exist
}

但该代码不起作用,甚至无法访问该路线,任何帮助将不胜感激,谢谢。

标签: phplaravel

解决方案


我认为这可能有效,

Route::get('itemsImages/{filename}', function ($filename)
{
  $path = app_path('public/images/itemsImages') . '/' . $filename;
  $response = null;
  if (file_exists($path))
  {
    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);      
  }
  else
  {
    dd($path);
    //does not exist
  }
  return $response;
})->name('route.name');

我没有测试上面的代码,所以告诉我是否适合你。


推荐阅读