Drupal 8 file entity cheat sheet

A file on disk can be managed via standard PHP calls, or using Drupal’s File entity.  Ideally, you’ll create a file entity instance, giving you easy control of the file within the site's file system.  If this is a managed file, it will have a file ID assigned to it in the database.  Simply pass the file ID to the static load() method, or create a new file instance.

Assume we're working with a white paper PDF stored in the /sites/default/files/whitepapers directory, with the public:// pointing to Drupal's default location of /sites/default/files.  Therefore, our white papers are stored in public://whitepapers.

With the file object instantiated, you can easily work with the file.

Drupal 8 makes file upload to a managed file easy. To upload with the Form API, in your build function, add a managed_file element.

If a file is located at a remote location, system_retrieve_file() is a useful function to download the file and insert the file entry.