How to create a file programmatically in Drupal 8 ?
Create a file with Drupal 8
Example:
// Programmatically create files.
use Drupal\file\Entity\File;
$file = File::create([
'uid' => 1,
'filename' => 'test.txt',
'uri' => 'public://page/test.txt',
'status' => 1,
]);
$file->save();
NOTE : This will not create a file in the DB but not in the disk.
To save data: You must do like that:
$dir = dirname($file->getFileUri());
if (!file_exists($dir)) {
mkdir($dir, 0770, TRUE);
}
file_put_contents($file->getFileUri(), "test");
$file->save();
And also:
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'mymodule', 'user',$uid);
$file->save();
Solution 2.
You can create a file and save data at once.
$file = file_save_data($value, "public://$dir/$filename", FILE_EXISTS_RENAME);
Get the real file path:
$path = drupal_realpath($file->getFileUri());
It may also work in this way (not tested)
$handle = fopen('<path to local file>', 'r');
$file = file_save_data($handle, 'public://<filename>');
fclose($handle);
Drupal File folders:
Drupal use 3 folders to store file.
private://
Private files directory
public://
Public files directory
temporary://
Tempory files directory