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 directorypublic://
Public files directorytemporary://
Tempory files directory
Comments
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 .
file save
Información muy útil gracias.
Add new comment