创建文件夹之前我需要知道文件夹是否存在,这是因为我在里面存储了图片,我担心如果覆盖文件夹,图片会被删除。 我必须创建一个文件夹的代码如下
$path = public_path().'/images';
File::makeDirectory($path, $mode = 0777, true, true);
我该怎么做?
用途:
if (!file_exists($path)) {
// path does not exist
}
在 Laravel 中:
if(!File::exists($path)) {
// path does not exist
}
注意:在 Laravel 中
从$path
文件夹开始,所以如果你想检查public
文件夹'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 Facade的这个方法:
use Illuminate\Support\Facades\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);
}
不要忘记使用 use Illuminate\Support\Facades\File;
方式-4:
if(!File::exists($backupLoc)) {
Storage::makeDirectory($backupLoc, 0755, true, true);
}
这样你必须将配置放在config文件夹中 文件系统.php 。 [不推荐,除非您使用外部磁盘]
我通常会在每个文件的图像中创建随机文件夹,这对加密 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);
}