Create a file with Drupal 8 | Drupal 8

Create a file with Drupal 8

Submitted by editor on Sat, 11/28/2015 - 19:06

How to create a file programmatically in Drupal 8 ?


// Programmatically create files.
use Drupal\file\Entity\File;
$file = File::create([
  'uid' => 1,
  'filename' => 'test.txt',
  'uri' => 'public://page/test.txt',
  'status' => 1,

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");

And also:
        $file_usage = \Drupal::service('file.usage');
        $file_usage->add($file, 'mymodule', 'user',$uid);

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>');

Drupal File folders:

Drupal use 3 folders to store file.

private://    Private files directory
public://    Public files directory
temporary://    Tempory files directory



Nick (not verified)

Fri, 04/07/2017 - 23:15

"NOTE : This will not create a file in the DB but not in the disk."

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.