Helpex - Trao đổi & giúp đỡ Đăng nhập
33

Tôi muốn tự động tạo danh sách tất cả các hình ảnh trong thư mục chung của mình, nhưng dường như tôi không thể tìm thấy bất kỳ đối tượng nào có thể giúp tôi thực hiện việc này.

Các Storagelớp học có vẻ như một ứng cử viên tốt cho công việc, nhưng nó chỉ cho phép tôi để tìm kiếm các file trong thư mục lưu trữ, mà nằm ngoài thư mục công cộng.

33 hữu ích 0 bình luận 78k xem chia sẻ
43

Bạn có thể tạo một đĩa khác cho lớp Lưu trữ. Đây sẽ là giải pháp tốt nhất cho bạn theo ý kiến ​​của tôi.

Trong config / filesystems.php trong mảng đĩa thêm thư mục mong muốn của bạn. Các công thư mục trong trường hợp này.

    'disks' => [

    'local' => [
        'driver' => 'local',
        'root'   => storage_path().'/app',
    ],

    'public' => [
        'driver' => 'local',
        'root'   => public_path(),
    ],

    's3' => '....'

Sau đó, bạn có thể sử dụng lớp Storage để làm việc trong thư mục chung của mình theo cách sau:

$exists = Storage::disk('public')->exists('file.jpg');

Các $ tồn tại biến sẽ cho bạn biết nếu file.jpg tồn tại bên trong các công thư mục vì đĩa lưu trữ 'công cộng' điểm đến thư mục công cộng của dự án.

Bạn có thể sử dụng tất cả các phương pháp Lưu trữ từ tài liệu, với đĩa tùy chỉnh của mình. Chỉ cần thêm phần đĩa ('công khai').

 Storage::disk('public')-> // any method you want from 

http://laravel.com/docs/5.0/filesystem#basic-usage

Chỉnh sửa sau:

Mọi người phàn nàn rằng câu trả lời của tôi không đưa ra phương pháp chính xác để liệt kê các tệp, nhưng ý định của tôi là không bao giờ bỏ một dòng mã mà op copy / paste vào dự án của mình. Tôi muốn "dạy" anh ta, nếu tôi có thể sử dụng từ đó, cách sử dụng Laravel Storage, thay vì dán một số mã.

Dù sao, các phương pháp thực tế để liệt kê các tệp là:

$files = Storage::disk('public')->files($directory);

// Recursive...
$files = Storage::disk('public')->allFiles($directory);

Và phần cấu hình và nền ở trên, trong câu trả lời ban đầu của tôi.

43 hữu ích 5 bình luận chia sẻ
44

Storage::disk('local')->files('optional_dir_name');

hoặc chỉ một loại tệp nhất định

array_filter(Storage::disk('local')->files(),
    //only png's
    function ($item) {return strpos($item, '.png');}
);

Lưu ý rằng đĩa laravel có files()allfiles(). allfileslà đệ quy.

44 hữu ích 2 bình luận chia sẻ
27

Cân nhắc sử dụng cầu . Không cần phải phức tạp hóa PHP đơn giản với các lớp / phương thức trợ giúp trong Laravel 5.

<?php
foreach (glob("/location/for/public/images/*.png") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>
27 hữu ích 1 bình luận chia sẻ
5

Để liệt kê tất cả các tệp trong thư mục, hãy sử dụng cái này

  $dir_path = public_path() . '/dirname';
   $dir = new DirectoryIterator($dir_path);
  foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {

    }
    else {

    }
}
5 hữu ích 1 bình luận chia sẻ
2

Để liệt kê tất cả hình ảnh trong dir công khai của bạn, hãy thử cách này: xem tại đây btw http://php.net/manual/en/class.splfileinfo.php

  function getImageRelativePathsWfilenames(){

      $result = [];

    $dirs = File::directories(public_path());

    foreach($dirs as $dir){
      var_dump($dir); //actually string: /home/mylinuxiser/myproject/public"
      $files = File::files($dir);
      foreach($files as $f){
        var_dump($f); //actually object SplFileInfo
        //object(Symfony\Component\Finder\SplFileInfo)#628 (4) {
        //["relativePath":"Symfony\Component\Finder\SplFileInfo":private]=>
        //string(0) ""
        //["relativePathname":"Symfony\Component\Finder\SplFileInfo":private]=>
        //string(14) "text1_logo.png"
        //["pathName":"SplFileInfo":private]=>
        //string(82) "/home/mylinuxiser/myproject/public/img/text1_logo.png"
        //["fileName":"SplFileInfo":private]=>
        //string(14) "text1_logo.png"
        //}

        if(ends_with($f, ['.png', '.jpg', '.jpeg', '.gif'])){
          $result[] = $f->getRelativePathname(); //prefix your public folder here if you want
        }
      }
    }
    return $result; //will be in this case ['img/text1_logo.png']
  }
2 hữu ích 1 bình luận chia sẻ
2

Bạn có thể dùng FilesystemReader::listContents

Storage::disk('public')->listContents();

Câu trả lời mẫu ...

[
  [
    "type" => "file",
    "path" => ".gitignore",
    "timestamp" => 1600098847,
    "size" => 27,
    "dirname" => "",
    "basename" => ".gitignore",
    "extension" => "gitignore",
    "filename" => "",
  ],
  [
    "type" => "dir",
    "path" => "avatars",
    "timestamp" => 1600187489,
    "dirname" => "",
    "basename" => "avatars",
    "filename" => "avatars",
  ]
]
2 hữu ích 1 bình luận chia sẻ
1

Bạn có thể nhận được tất cả các tệp đang thực hiện:

use Illuminate\Support\Facades\Storage;

..

$files = Storage::disk('local')->allFiles('public');
1 hữu ích 0 bình luận chia sẻ
0

Vui lòng sử dụng mã sau và lấy tất cả các thư mục con của một thư mục cụ thể trong thư mục chung. Khi một số người nhấp vào thư mục, nó sẽ liệt kê các tệp bên trong mỗi thư mục.

Tệp điều khiển

 public function index() {

    try {

        $dirNames = array();  
        $this->folderPath = 'export'.DS.str_replace( '.', '_', $this->getCurrentShop->getCurrentShop()->shopify_domain ).DS.'exported_files';
        $getAllDirs = File::directories( public_path( $this->folderPath ) );

        foreach( $getAllDirs as $dir ) {

            $dirNames[] = basename($dir);

        }
        return view('backups/listfolders', compact('dirNames'));

    } catch ( Exception $ex ) {
        Log::error( $ex->getMessage() );
    }



}

public function getFiles( $directoryName ) {

    try {
        $filesArr = array();
        $this->folderPath = 'export'.DS.str_replace( '.', '_', $this->getCurrentShop->getCurrentShop()->shopify_domain ).DS.'exported_files'. DS . $directoryName;
        $folderPth = public_path( $this->folderPath );
        $files = File::allFiles( $folderPth ); 
        $replaceDocPath = str_replace( public_path(),'',$this->folderPath );

        foreach( $files as $file ) {

            $filesArr[] = array( 'fileName' => $file->getRelativePathname(), 'fileUrl' => url($replaceDocPath.DS.$file->getRelativePathname()) );

        }

        return view('backups/listfiles', compact('filesArr'));

    } catch (Exception $ex) {
        Log::error( $ex->getMessage() );
    }


}

Tuyến đường (Web.php)

Route::resource('displaybackups', 'Displaybackups\BackupController')->only([ 'index', 'show']);

Route :: get ('get-files / {directoryName}', 'Displaybackups \ BackupController @ getFiles');

Xem tệp - Danh sách thư mục

@foreach( $dirNames as $dirName)
    <div class="col-lg-3 col-md-3 col-sm-4 align-center">
        <a href="get-files/{{$dirName}}" class="btn btn-light folder-wrap" role="button">
            <span class="glyphicon glyphicon-folder-open folderIcons"></span>
            {{ $dirName }}
        </a>
    </div>
@endforeach

Xem - Liệt kê Tệp

@foreach( $filesArr as $fileArr)
    <div class="col-lg-2 col-md-3 col-sm-4">
        <a href="{{ $fileArr['fileUrl'] }}" class="waves-effect waves-light btn green folder-wrap">
            <span class="glyphicon glyphicon-file folderIcons"></span>
            <span class="file-name">{{ $fileArr['fileName'] }}</span>
        </a>
    </div>
@endforeach
0 hữu ích 0 bình luận chia sẻ
loading
Không tìm thấy câu trả lời bạn tìm kiếm? Duyệt qua các câu hỏi được gắn thẻ php laravel storage , hoặc hỏi câu hỏi của bạn.

Có thể bạn quan tâm

loading