【问题标题】:How to find file without specific file extension in laravel storage?如何在 laravel 存储中查找没有特定文件扩展名的文件?
【发布时间】:2016-08-22 05:30:58
【问题描述】:

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

喜欢这个"filename.*"

Storage::get("filename.*")

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

【问题讨论】:

  • 试试Storage::get("filename\.*")
  • @RohanKumar 不适合我。我正在使用 laravel 5.0。
  • This 是这个问题的一个更通用的版本:如何将 glob 模式与Storage 一起使用。由于glob 并非在每个系统上都可用,Storage 不能直接实现它(尽管一些透明的包装器会非常受欢迎!)。该解决方案是一种与the answer by jedrzej.kurylo here 非常相似的解决方法:只需获取整个列表并使用 RegExp(或其他方法)对其进行过滤。

标签: php laravel laravel-5 storage


【解决方案1】:

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

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

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

// 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);
}

【讨论】:

  • 你被蜂鸣器咬了。我在想同样的解决方案。由于正则表达式,只有我得到了调整。我删除了 ^ 以适合我的搜索。无论如何,非常感谢您的宝贵时间。我会将此标记为正确。拯救了我的一天!
【解决方案2】:

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

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

请参阅此处的参考: http://laravel-recipes.com/recipes/143/finding-files-matching-a-pattern

【讨论】:

【解决方案3】:

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

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

// 来自:

$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...
    }
}

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

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 2023-01-13
      • 2011-08-21
      • 2019-07-21
      • 2012-01-26
      相关资源
      最近更新 更多