如何从特定文件夹中返回随机资产?

时间:2016-08-01 14:27:34

标签: laravel laravel-5.1

我需要创建一个从特定目录返回随机图像或视频的路径,我该如何实现?

1 个答案:

答案 0 :(得分:0)

也许是这样的

Route::get('/random_media/', function() {

    // Get random files and pick one.
    $folder_path = public_path()."/your/path/here/"; // in my test case it's under /public folder
    $files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($folder_path));
    $randomFile = $files[array_rand($files)]; // if 5 files found, random int between 0 and 4
    // Display it
    $file = File::get($folder_path.$randomFile);
    $response = Response::make($file, 200);
    $response->header('Content-Type', mime_content_type($folder_path.$randomFile));
    return $response;

});

使用preg_grep而不是glob()。看到这个答案:https://stackoverflow.com/a/8541256/2468160

Tested

我的laravel版本是5.2.39,但我希望它适用于5.1。*