#1 辅助函数storage_path()和public_path()
storage_path()和public_path()这两个辅助函数返回storage和public目录的完整路径。
storage_path()辅助函数返回的storage目录的完整路径,其实是php artisan storage:link生成的链接地址。
$path = 'articles';
return [
storage_path($path),
public_path($path),
];
//output
//[
// "/home/vagrant/code/top/storage/articles",
// "/home/vagrant/code/top/public/articles"
//]
#2 遍历文件的函数
files 方法返回指定目录下的所有文件的数组。allFiles 方法返回指定目录下包含子目录的所有文件的数组;
console下无法遍历public下面的文件夹,只能遍历storage的
$path = 'article';
//返回 SplFileInfo 对象的数组
$fileList1 = File::allfiles(Storage::disk('public')->path($path));
//返回storage下相对路径的数组,要转为绝对路径,用Storage::disk('public')->path($file)
$fileList2 = Storage::disk('public')->allFiles($path);
#3 综合实例
项目中有一个需求,业务部门提供 姓名+身份证号.pdf 的学历复印件,需要批量导入到员工的学历附件中
/**
* 批量导入逻辑
* @param $path 放在storage里面的目录
*/
public function import($path)
{
$files = Storage::disk('public')->allFiles($path);
collect($files)
->each(function ($file, $key) {
// import/education/李百川+440111199001011111.pdf
$this->output->writeln("{$key}、开始导入{$file}..");
$basename = basename($file);
$fileInfo = explode('.', $basename);
//$suffix = $fileInfo[1];
$filename = $fileInfo[0];
$empInfo = explode('+', $filename);
if (count($empInfo) >= 2) {
$employee = Employee::query()
->where('idCard', $empInfo[1])
->first();
if ($employee) {
$education = $employee->educationList()->orderByDesc('graduateDate')->first();
if ($education && $education->media_count) {
$this->output->writeln("{$key}、{$file}已经导入过了!");
return;
}
if ($education && $education->media_count == 0) {
$education
->addMedia(Storage::disk('public')->path($file))
->toMediaCollection('education-pdf');
$this->output->success("{$key}、导入{$file}成功!");
return;
}
}
}
Log::channel('file_import')->error("{$file}导入失败!");
$this->output->warning("{$key}、导入{$file}失败!");
});
}