![](/img/trans.png)
[英]how to check if folder exists before upload images to digital ocean space
[英]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 中
$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 门面的这个方法:
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 中。 [不推荐,除非您使用外部磁盘]
我通常在图像中为每个文件创建随机文件夹,这有助于加密 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.