簡體   English   中英

如何在laravel中創建文件夾之前檢查文件夾是否存在?

[英]How to check if a folder exists before creating it in laravel?

我需要在創建之前知道文件夾是否存在,這是因為我將圖片存儲在里面,我擔心如果覆蓋文件夾,圖片會被刪除。 我必須創建一個文件夾的代碼如下

$path = public_path().'/images';
File::makeDirectory($path, $mode = 0777, true, true);

我該怎么做?

參見: file_exists()

用法:

if (!file_exists($path)) {
    // path does not exist
}

在 Laravel 中:

if(!File::exists($path)) {
    // path does not exist
}

注意:在 Laravel 中$pathpublic文件夾開始,所以如果你想檢查'public/assets'文件夾$path = 'assets'

使用 Laravel,您可以使用:

$path = public_path().'/images';
File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);

順便說一句,你也可以將子文件夾作為參數放在 Laravel 路徑輔助函數中,就像這樣:

$path = public_path('images/');

你也可以調用 File 門面的這個方法:

File::ensureDirectoryExists('/path/to/your/folder')

如果它不存在,則創建一個文件夾,如果存在,則什么也不做

在 Laravel 5.x/6 中,你可以使用Storage Facade來做到這一點:

use Illuminate\Support\Facades\Storage;

$path = "path/to/folder/";

if(!Storage::exists($path)){
    Storage::makeDirectory($path);
}

方式-1:

if(!is_dir($backupLoc)) {

    mkdir($backupLoc, 0755, true);
}

方式-2:

if (!file_exists($backupLoc)) {

    mkdir($backupLoc, 0755, true);
}

方式-3:

if(!File::exists($backupLoc)) {

    File::makeDirectory($backupLoc, 0755, true, true);
}

不要忘記使用 Illuminate\Support\Facades\File;

方式-4:

if(!File::exists($backupLoc)) {

    Storage::makeDirectory($backupLoc, 0755, true, true);
}

這樣,您必須將配置首先放在配置文件夾 filesystems.php 中。 [不推薦,除非您使用外部磁盤]

推薦的方法是使用

if (!File::exists($path))
{

}

查看源代碼

如果您查看代碼,它正在調用file_exists()

我通常在圖像中為每個文件創建隨機文件夾,這有助於加密 url,因此公眾會發現通過簡單地輸入目錄的 url 來查看文件更加困難。

// Check if Logo is uploaded and file in random folder name -  
if (Input::hasFile('whatever_logo'))
            {
                $destinationPath = 'uploads/images/' .str_random(8).'/';
                $file = Input::file('whatever_logo');
                $filename = $file->getClientOriginalName();                
                $file->move($destinationPath, $filename);
                $savedPath = $destinationPath . $filename;
                $this->whatever->logo = $savedPath;
                $this->whatever->save();
            }

            // otherwise NULL the logo field in DB table.
            else 
            {
                $this->whatever->logo = NULL;    
                $this->whatever->save();    
            }            

這對我很有用

if(!File::exists($storageDir)){
    File::makeDirectory($storageDir, 0755, true, true);
    $img->save('Filename.'.png',90);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM