You are here

public function AjaxController::saveFile in S3 File System CORS Upload 8

Save the file details to the managed file table.

1 string reference to 'AjaxController::saveFile'
s3fs_cors.routing.yml in ./s3fs_cors.routing.yml
s3fs_cors.routing.yml

File

src/Controller/AjaxController.php, line 213

Class

AjaxController
Default controller for the s3fs_cors module.

Namespace

Drupal\s3fs_cors\Controller

Code

public function saveFile($file_path, $file_name, $file_size, $field_name) {
  $user = $this
    ->currentUser();

  // Decode the "/" chars from file path.
  $file_path = str_replace('::', '/', $file_path);

  // Remove the root folder from the file path if specified.
  $config = $this
    ->config('s3fs.settings');
  if (!empty($config
    ->get('root_folder'))) {
    $root_folder = $config
      ->get('root_folder');
    $file_path = str_replace($root_folder . '/', '', $file_path);
  }
  $file_uri = 's3://' . $file_path;

  // Record the uploaded file in the s3fs cache. This needs to be done before
  // the file is saved so the the filesize can be found from the cache.
  $wrapper = new S3fsStream();
  $wrapper
    ->writeUriToCache($file_uri);

  // Convert URLs back to their proper (original) file stream names.
  $public_folder = 's3://' . ($config
    ->get('public_folder') ?: 's3fs-public');
  $private_folder = 's3://' . ($config
    ->get('private_folder') ?: 's3fs-private');
  if (strpos($file_uri, $public_folder) === 0 || strpos($file_uri, $private_folder) === 0) {
    $file_uri = str_replace([
      $public_folder,
      $private_folder,
    ], [
      'public:/',
      'private:/',
    ], $file_uri);
  }
  $file_mime = $this->mimeType
    ->guess($file_name);
  $values = [
    'uid' => $user
      ->id(),
    'status' => 0,
    'filename' => $file_name,
    'uri' => $file_uri,
    'filesize' => $file_size,
    'filemime' => $file_mime,
    'source' => $field_name,
  ];
  $file = File::create($values);
  $errors = [];
  $errors = array_merge($errors, $this
    ->moduleHandler()
    ->invokeAll('file_validate', [
    $file,
  ]));
  if (empty($errors)) {
    $file
      ->save();
    $values['fid'] = $file
      ->id();
    $values['uuid'] = $file
      ->uuid();
  }
  else {
    $file
      ->delete();
    $values['errmsg'] = implode("\n", $errors);
  }
  return new JsonResponse($values);
}