Drupalwoo ☉

Managing file uploads with Drupal's File API and custom directories

Uploading a PDF through a Drupal form looks unremarkable: pick a file, press save, move on. Underneath, the file follows a path you rarely see. It lands in the site's configured upload directory, inherits a generated filename, and becomes a managed file entity only if the form was built to create one. On a busy site that default folder turns into a dumping ground for logos, tender documents, application forms and export spreadsheets. The File API gives you programmatic control over where files live, what they are called and who can reach them.

This guide covers the pieces needed to build a reliable custom upload workflow: creating a directory structure that survives a rebuild, validating files before they are stored, saving them as managed entities or raw files, and wiring everything into Form API and custom fields. The security side matters just as much, because a custom directory is only worth having if it stays tidy, private and free of executable uploads. Examples use Drupal 9, 10 and 11 APIs, and the same patterns apply whether you are a solo developer in Bendigo or an agency team shipping a project for a Melbourne client.

The examples assume Australian deployments: sites hosted in Sydney or Melbourne, teams working across AEST and AEDT, and clients who care about where their documents sit on disk. Australian spelling is used throughout, so licence stays a noun and organisation keeps its s. A few local wrinkles also turn up in the naming, retention and accessibility notes below, and they are worth reading before you copy a directory layout from an American tutorial.

Why custom directories change the upload workflow

Every Drupal site starts life with one configured upload directory, usually sites/default/files, and the public and private file schemes point at two roots beneath it. That arrangement works for a brochure site with ten images. It falls over the moment a client asks for invoices to be kept apart from job applications, or for a government tender portal where each submission needs its own folder. The File API lets you build a hierarchy under either scheme and store files inside it, while still recording the file in Drupal's database so permissions and deletion behave sensibly.

Comparing the common approaches:

Approach Where the file ends up Directory control Usage tracking Suits
Core file widget The site's default files directory Only the configured root Yes Straightforward article attachments
File API with managed entities Any path under public:// or private:// Full Yes Applications, reports, client documents
Unmanaged files via file_unmanaged_* Any path the code writes to Full No Very large files, bulk imports
Hand-rolled PHP upload handling Wherever the script chooses Full No Legacy or unusual pipelines

The middle two rows are where most production sites land. Managed entities give you a filename, a MIME type, an owner, revision history and reference tracking, so deleting the node that owns a document can remove the document too. Unmanaged files are faster and simpler, which makes them the right call for gigabyte-scale uploads that would bog down the database, but you lose that automatic cleanup. Knowing which row you are in makes the rest of the design easier.

Creating a directory structure that lasts

Directories should be created deliberately, not as a side effect of a failed fopen() call. Drupal's Filesystem service exposes prepareDirectory(), which creates a path and its parents in one go and reports success with a boolean. Use the service rather than raw mkdir() calls so the code behaves the same whether a deployment sits on shared hosting in Brisbane or on a container platform in Melbourne.

$file_system = \Drupal::service('file_system');
$directory = 'public://uploads/tenders/2026-02';

$prepared = $file_system->prepareDirectory(
  $directory,
  $file_system::CREATE_DIRECTORY | $file_system::MODIFY_PERMISSIONS
);

if (!$prepared) {
  throw new \RuntimeException('Unable to prepare ' . $directory);
}

Core creates folders with wide-open permissions, so tighten them where the host allows it with chmod($directory, 0755), and keep executable PHP out of the tree entirely. If the uploads root can live outside the document root, ask your host to alias it at the web server level; if not, rely on the server configuration described later.

Naming deserves thought too. A structure such as uploads/invoices/2026-07/gst/ lets a bookkeeper in Adelaide find a document without asking anyone for a path, and it avoids the scattering that happens when every file is timestamped but not categorised. Stick to lowercase ASCII, hyphens and forward slashes, because users across Australia often upload files with accents in the name and those characters cause trouble in some shells. If you must preserve the original name, keep a sanitised copy on disk and store the friendly version as metadata.

Validating uploads and saving them correctly

Three checks should run before a file is accepted: the extension, the size and the real content. Extensions alone are trivially spoofed, so pair file_validate_extensions() with a MIME check using file_get_mimetype(), and use file_validate_is_image() or file_validate_image_resolution() when you expect pictures.

$errors = [];
$allowed = ['pdf', 'docx', 'png', 'jpg'];
$max_bytes = 20 * 1024 * 1024;

$errors = file_validate_extensions($filename, $allowed);
$errors = array_merge($errors, file_validate_size($size, $max_bytes));

if ($errors) {
  foreach ($errors as $message) {
    \Drupal::logger('uploads')->notice($message);
  }
}

The error text should be written for a non-technical reader, which is more than politeness in an Australian context. Commonwealth agencies are expected to meet WCAG 2.1 AA under the Australian Government Digital Service Standard, and state health providers follow similar rules. A rejected file needs a clear summary that announces itself to screen readers, identifies the offending field and keeps focus near the message, rather than a red border nobody notices.

Saving then depends on which row of the comparison you chose. For managed files, file_save() copies the source into your directory, generates a unique filename if needed and returns a file entity you can enrich and store.

$file = file_save($data, 'public://uploads/tenders/2026-02/tender.pdf', FILE_EXISTS_RENAME);
$file->setOwnerId($uid);
$file->save();

$url = file_create_url($file->uri());

For very large files, file_unmanaged_copy() or file_unmanaged_move() writes straight to the destination without a database row. Australian universities and TAFEs routinely handle multi-gigabyte lecture recordings, and enrolment peaks in February and July can push a shared host to its limits; an unmanaged path or a streamed upload to an S3 bucket in ap-southeast-2 handles that volume better than a managed entity. The trade-off is real, though, since nothing will clean up those orphans for you.

Wiring the File API into forms and entities

Form API's file element does the heavy lifting for validation, but the submitted file still needs moving into your structure. In Drupal 9 and later the element places the upload in the temporary scheme and hands you a file object on submit, ready to be relocated.

$form['attachment'] = [
  '#type' => 'file',
  '#title' => 'Signed tender document',
  '#upload_validators' => [
    'FileExtensionLimit' => ['pdf docx'],
    'FileSizeLimit' => [20971520],
  ],
];

In the submit handler, copy the temporary file into your prepared directory, optionally create a managed entity for it, and attach the reference to the parent content so the usage table stays accurate. Where the destination depends on the submitted values, such as a channel ID or a node ID, prepare the directory inside the submit handler rather than at build time.

Hooks make the behaviour reusable across a site. hook_file_presave() can adjust the URI before the entity is written, hook_file_insert() can fire off side effects such as generating a thumbnail, and hook_entity_insert() lets you organise attachments that arrive with a node rather than a form. For bulk jobs, wrap the copies in a batch operation so a busy afternoon of uploading does not time out the request. For the wider configuration picture — content types, roles and editorial workflow — the Drupalwoo site guides cover the surrounding setup in more detail.

Keeping directories secure and tidy

A directory you created is a directory the web server will happily serve. Disable directory listing, and make sure the server treats the upload folder as inert content: no PHP handler, no script execution, no CGI. Apache deployments typically drop a .htaccess file into the folder that resets the engine, while nginx setups need a matching location block with the interpreter removed. Without that step, a file with a .php extension can become a remote shell, which is the fastest way to lose an Australian client's trust and their data at the same time.

Cleanup needs a routine of its own. Managed files disappear when their referencing entity is deleted, but files in custom directories or unmanaged paths linger until something removes them. A cron job that reports orphans older than a set threshold, backed by a review step, keeps storage costs down. Retention periods are worth checking with the client rather than guessing: Australian business records often need to be kept for five years, sometimes seven, and privacy obligations under the Privacy Act 1988 and state legislation can add their own requirements on contractor and client documents.

Two checklists keep the build honest:

Before development starts:

Before go-live:

A Sydney agency can turn a whole client's upload workflow around in an afternoon, but only if the directory rules, validation messages and cleanup routine were agreed before the first file was written rather than after.