Example #1
0
 public static function saveTempFileByFileContent($fileContent, User $user, $diskName = null)
 {
     $rootDir = "temp-file";
     $fs = Storage::disk($diskName);
     $md5 = md5($fileContent);
     $sha1 = sha1($fileContent);
     $size = strlen($fileContent);
     $diskName = $diskName ? $diskName : Storage::getDefaultDriver();
     $name = $md5 . '-' . $sha1;
     $ext = '.tmp';
     $now = Carbon::now();
     $toDirPath = $rootDir . '/' . $now->year . '/' . $now->month . '/' . $now->day;
     $toFilePath = $toDirPath . '/' . $md5 . '-' . $sha1 . '-' . str_random();
     try {
         $fs->makeDirectory($toDirPath);
     } catch (\Exception $e) {
         if (!$fs->exists($toDirPath)) {
             throw $e;
         }
     }
     if (!$fs->exists($toFilePath)) {
         $fs->put($toFilePath, $fileContent);
     }
     $basicFile = new BasicFile();
     $basicFile->md5 = $md5;
     $basicFile->sha1 = $sha1;
     $basicFile->size = $size;
     $basicFile->disk = $diskName;
     $basicFile->path = $toFilePath;
     $fileModel = new FileModel();
     $fileModel->name = $name;
     $fileModel->ext = $ext;
     $fileModel->mime = '';
     $fileModel->user()->associate($user);
     $fileModel->baseFile()->associate($basicFile);
     return $fileModel;
 }