2016-08-01 55 views
0

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

+2

我会使用'glob()'将目录中的所有文件返回为arr唉。在这一点上,你可以得到数组的长度,并使用'rand()'返回一个介于0和数组长度之间的随机数。将它作为数组索引插入,并从目录中随机选择一个文件。 –

+0

您可以请upvote我的答案或接受它,如果它的工作。 –

回答

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而不是水珠的()。看到这样的回答:https://stackoverflow.com/a/8541256/2468160

Tested

我的laravel版本是5.2.39,但我希望它能在5.1上工作。*

相关问题