Search code examples
phpfiledrupaldrupal-7

Drupal 8: The file could not be created


I have below code to upload excel file provided by API in base64_encode format.

I would like to download that file and save in to file system.

public function import(Request $request) {

    if ($request->getMethod() === 'POST') {
      $data = json_decode($request->getContent(), TRUE);

      $directory = 'public://import/';

      // create directory if it does not exist
      file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);

      $uri = $directory. $data['name'];
      $files_data = preg_replace('#^data:application/\w+;base64,#i', '', $data['data']);
      $file_data = base64_decode($files_data);
      $file = file_save_data($file_data, $uri, FILE_EXISTS_RENAME);
      echo $file->id();
    }
} 

It goes to below function and gives error, although I have created tmp folder on project root and given needed 777 permission.

/drupal/web/core/includes/file.inc

function file_unmanaged_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  // Write the data to a temporary file.
  $temp_name = drupal_tempnam('temporary://', 'file');
  if (file_put_contents($temp_name, $data) === FALSE) {
    \Drupal::messenger()->addError(t('The file could not be created.'));
    return FALSE;
  }

  // Move the file to its final destination.
  return file_unmanaged_move($temp_name, $destination, $replace);
}

What I am missing? It is not converting and saving file.


Solution

  • Usually this happen because of wrong temporary location and permission, what I suggest you is go to /admin/config/media/file-system and make sure you set Temporary Directory correctly. if its fine. check the permission of it. you need to set it writeable by webservice.