如何从Laravel的资源中获取图像?

时间:2016-08-03 07:09:46

标签: laravel laravel-5

我将所有用户文件上传到目录:

/resources/app/uploads/

我尝试通过完整路径获取图像:

http://localhost/resources/app/uploads/e00bdaa62492a320b78b203e2980169c.jpg

但我得到错误:

NotFoundHttpException in RouteCollection.php line 161:

如何通过这条道路获得图像?

现在我尝试在根目录中的/ public / uploads /目录中上传文件:

$destinationPath = public_path(sprintf("\\uploads\\%s\\", str_random(8)));
$uploaded = Storage::put($destinationPath. $fileName, file_get_contents($file->getRealPath()));

它给了我错误:

Impossible to create the root directory 

4 个答案:

答案 0 :(得分:19)

您可以制作专门用于显示图像的路线。

例如:

Route::get('/resources/app/uploads/{filename}', function($filename){
    $path = resource_path() . '/app/uploads/' . $filename;

    if(!File::exists($path)) {
        return response()->json(['message' => 'Image not found.'], 404);
    }

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});

现在你可以转到localhost/resources/app/uploads/filename.png,它应该显示图像。

答案 1 :(得分:11)

您可以在刀片文件上尝试此操作。 images文件夹位于公用文件夹

<img src="{{URL::asset('/images/image_name.png')}}" />

对于Laravel的更高版本(上面的5.7):

<img src = "{{ asset('/images/image_name.png') }}" />

答案 2 :(得分:6)

如果您想从刀片中调用它,请尝试output { elasticsearch { hosts => ["localhost:9200"] document_id => "%{ip}" } }

ip如果您想在控制器中使用它。

希望有帮助=)

答案 3 :(得分:0)

正如@alfonz 提到的, resource_path() 是获取资源文件夹目录的正确方法。 获取特定文件位置,代码如下

 $path = resource_path() . '/folder1/folder2/filename.extension';