如何在 laravel 存储中查找没有特定文件扩展名的文件?

How to find file without specific file extension in laravel storage?

如何在 laravel 存储中按名称查找没有特定扩展名的文件?

像这样"filename.*"

Storage::get("filename.*")

我试过了,但似乎不起作用。它搜索具有特定扩展名的特定文件。

Storage::get() 将文件路径作为参数,returns 由该路径标识的单个文件的内容或抛出 FileNotFoundException 如果找不到文件。

路径 不支持通配符 - 一个原因可能是可能有多个文件与带有通配符的路径相匹配,这会破坏一个规则Storage::get() 返回单个文件。扫描整个文件夹也会慢很多,尤其是远程存储。

但是,您可以使用 Storage facade 提供的其他功能来获得您想要的东西。首先,列出您的存储内容 - 这将为您提供所有可用文件的列表。然后自己过滤列表,得到匹配文件的列表。

// list all filenames in given path
$allFiles = Storage::files('');

// filter the ones that match the filename.* 
$matchingFiles = preg_grep('/^filename\./', $allFiles);

// iterate through files and echo their content
foreach ($matchingFiles as $path) {
  echo Storage::get($path);
}

不要相信你所看到的。进入并获取文件的文本

$pic = 'url/your.file';
$ext = image_type_to_mime_type(exif_imagetype($pic));
$ext = explode('/',$ext);
echo $ext[1];

接受的解决方案有效。但是我找到了另一个,我更喜欢它:

$matchingFiles = \Illuminate\Support\Facades\File::glob("{$path}/*.log");

参见此处的参考资料: http://laravel-recipes.com/recipes/143/finding-files-matching-a-pattern

对 jedrzej.kurylo 的答案进行了细微更改,并使用 laravel 8 合并了 wogsland 的答案:

'/^filename\./''/filename\./' 模式在我的情况下不起作用。

// From:

$matchingFiles = preg_grep('/^filename./', $allFiles);

// To:
$allFiles = Storage::disk('yourStorageDisk')->files('folder/path');
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp'];
$matchingFiles = preg_grep('{'.$image.'}', $allFiles);

foreach ($matchingFiles as $path) {
    // get real mime type
    $contentType = image_type_to_mime_type(exif_imagetype(asset($path)));

    // compare it with our allowed mime types
    if (in_array($contentType, $allowedMimeTypes)) {
        // do something here...
    }
}

这样我们就可以安全地获取文件或图片了。