How to create a file programmatically in 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
Comments5
not twice
"NOTE : This will not create a file in the DB but not in the disk."
Agreed, it should probably…
Agreed, it should probably say, "Note: This will create a file in the DB but not on the disk."
mistake in text?
"NOTE : This will not create a file in the DB but not in the disk.
To save data: You must do like that:"
I think there is one "not" too many in that sentence.
Read avatar user and diplay it
hi , i want to get th avatar user and display it, can you help me please .
In Drupal 9.3.3 doesn't work
Hi all.
The first solution in Drupal 9.3.3 seem doesn't work. I obtain two errors:
- Drupal\Core\File\Exception\FileNotExistsException: File 'private://pdf/yyy.pdf' could not be copied because it does not exist. in Drupal\Core\File\FileSystem->prepareDestination() (linea 459 di /var/www/html/test/web/core/lib/Drupal/Core/File/FileSystem.php)
- Drupal\Core\Entity\EntityStorageException: File 'private://pdf/yyy.pdf' could not be copied because it does not exist. in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (linea 811 di /var/www/html/test/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php)
Anyone have any idea? Maybe in 9.3.x has changed something in File management?
Alex.