#1 Auxiliary functionstorage_path()
andpublic_path()
The storage_path() and public_path() helper functions return the full path to the storage and public directories.
Storage_path () Is the full path of the storage directory returned by the helper function, which is actually the link address generated by 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"
/ /]
Copy the code
#2 Function to traverse the file
The files method returns an array of all files in the specified directory. The allFiles method returns an array of allFiles under the specified directory that contain subdirectories;
The public folder cannot be traversed under console, only storage folder can be traversed
$path = 'article';
// Returns an array of SplFileInfo objects
$fileList1 = File::allfiles(Storage::disk('public')->path($path));
Storage::disk('public')->path($file)
$fileList2 = Storage::disk('public')->allFiles($path);
Copy the code
#3 Comprehensive example
There is a requirement in the project that the business department should provide name + ID number. The PDF copy of education background needs to be imported into the attachment of employees’ education background in batches
/** * Batch import logic *@param$path Specifies the directory in storage */
public function import($path)
{
$files = Storage::disk('public')->allFiles($path);
collect($files)
->each(function ($file.$key) {
// import/education/ Li Baichuan +440111199001011111.pdf
$this->output->writeln("{$key}Start import{$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}Already imported!");
return;
}
if ($education && $education->media_count == 0) {
$education
->addMedia(Storage::disk('public')->path($file))
->toMediaCollection('education-pdf');
$this->output->success("{$key}, import,{$file}Success!");
return;
}
}
}
Log::channel('file_import')->error("{$file}Import failed!");
$this->output->warning("{$key}, import,{$file}Failure!");
});
}
Copy the code