首页 文章

Laravel部署:存储映像无法正常工作

提问于
浏览
0

将我的laravel项目从本地部署到Apache Web服务器之后,除了图像链接之外,所有工作都正常 . 这里的代码:

图像存储在:

storage/app/public/photos

在我运行命令之后:

php artisan storage:link

图片链接在:

public/storage/photos

控制器:

if ($request->hasFile('photo')) {
   $extension = $request->file('photo')->getClientOriginalExtension();
   $file = $request->file('photo');
   $photo = $file->storeAs('public/photos', 'foto-' . time() . '.' . $extension);
   $user->photo = $photo;
   $user->save();
}

图像在存储/应用/公共/照片上正确上传,并在公共/存储/照片中正确链接,但它不会显示在前端 .

在刀片中,我试图使用Storage :: url来检索路径

{{Storage::url($user->photo)}}

和资产()

{{asset($user->photo)}}

在这两种情况下,图像都不存在

公共图像路径是:

http://mywebsite.com/storage/photos/foto-1522914164.png

3 回答

  • 0

    您应该使用 url 函数以如下方式显示您的图像 .

    url($user->photo);
    
  • 0

    我建议更改控制器代码如下:

    if ($request->hasFile('photo')) {
      $extension = $request->file('photo')->getClientOriginalExtension();
      $file = $request->file('photo');
      $photoFileName = 'foto-' . time() . '.' . $extension;
      $photo = $file->storeAs('public/photos', $photoFileName);
      $user->photo = 'photos/' . $photoFileName;
      $user->save();
    }
    

    然后,您可以在刀片中使用 {{asset($user->photo)}} .

  • 0

    在我的网站空间上,似乎正确显示图像的唯一方法是创建一个读取和提供图像的自定义路径 .

    我这样解决了:

    我只在db中存储图像名称:

    if ($request->hasFile('photo')) {
        $extension = $request->file('photo')->getClientOriginalExtension();
        $file = $request->file('photo');
        $photoFileName = 'photo-' . $model->id . '.-' . time() . '.' . $extension;
        $photo = $file->storeAs('public/photos', $photoFileName);
        $store = $photoFileName;
    }
    

    然后,我创建了自定义路线,读取图像并显示它们:

    Route::get('storage/{filename}.{ext}', function ($filename, $ext) {
        $folders = glob(storage_path('app/public/*'), GLOB_ONLYDIR);
        $path = '';
        foreach ($folders as $folder) {
           $path = $folder . '/' . $filename . '.' . $ext;
           if (File::exists($path)) {
              break;
           }
        }
    
        if (!File::exists($path)) {
            abort(404);
        }
    
        $file = File::get($path);
        $type = File::mimeType($path);
    
        $response = Response::make($file, 200);
        $response->header('Content-Type', $type);
    
        return $response;
    });
    

    在刀片中,我使用存储来显示图像:

    {{ Storage::url($photo->photo) }}}
    

相关问题