File Storage
- Introduction
- Configuration
- Obtaining disk instances
- Retrieving files
- Storing files
- Deleting files
- Directories
- Failure modes
- Testing
Introduction
Applications store many kinds of files: user avatars, generated invoices, and nightly report exports. The dust::storage module provides a unified API across local filesystems, DUST Cloud Object Storage, and S3-compatible object stores, so your code reads and writes files identically whether they live locally or in the cloud.
Configuration
Files live on named disks, where each disk maps to either a local directory or an S3-compatible bucket. The FILESYSTEM_DISK environment variable selects the default disk used by top-level functions in dust::storage. dust-framework configures three disks out of the box:
| Disk | Location | Access |
|---|---|---|
local |
storage/app/private (default disk). |
Your handlers and temporary URLs. |
public |
storage/app/public. |
Publicly downloadable from /storage. |
s3 |
Bucket configured via AWS_* variables. |
Controlled by your bucket policy. |
Most applications only need these built-in disks. To add another disk, create a src/config/filesystems.rs configuration file starting from Filesystems::from_env and register your disk. Local disk roots are resolved relative to your application's base path:
// src/config/filesystems.rsuse dust::config::filesystems::{Filesystems, LocalDisk};use dust::config::{self, Env};#[config::section]fn filesystems(env: &Env) -> Filesystems { let mut filesystems = Filesystems::from_env(env); filesystems.add_disk("documents", LocalDisk::new("storage/app/documents")); filesystems}Register the module in src/config/mod.rs:
mod filesystems;The public disk
The public disk stores files intended to be publicly accessible, such as user avatars. dust-framework serves its files directly at /storage, so a file stored at avatars/1.png is served at https://example.com/storage/avatars/1.png.
Custom local disks are not served over HTTP until you assign a mount path. With only a mount path, files can only be downloaded via temporary URLs. Chain .public() to allow direct public downloads as well:
filesystems.add_disk( "images", LocalDisk::new("storage/app/images").mount("/images").public(),);filesystems.add_disk( "documents", LocalDisk::new("storage/app/documents").mount("/documents"),);With this configuration, a file stored at banners/hero.png on the images disk is served publicly at https://example.com/images/banners/hero.png, while files on the documents disk are only accessible under /documents via signed temporary URLs.
If one of your application routes matches the same path as a disk mount, your route takes precedence.
DUST Cloud Object Storage
When deploying to DUST Cloud, store uploaded and generated files in DUST Cloud Object Storage buckets instead of the local filesystem, since container disks are reset on each deploy and aren't shared across instances. DUST Cloud Object Storage works out of the box with no extra Cargo features or AWS SDK dependency.
When you attach a bucket to an environment in the DUST Cloud dashboard, dust-framework registers it automatically under the disk name you chose. That replaces any built-in disk with the same name (such as local or public), so your application can keep using local disks in development and switch to Cloud buckets in production without changing your code. If you mark a bucket as the environment's default disk in the dashboard, top-level dust::storage calls target that bucket automatically.
A bucket's visibility applies to all of its files. Files in a public bucket have public URLs served from the bucket's public domain, while files in a private bucket are only accessible through signed temporary URLs (valid for up to seven days). If your application stores both public and private files, attach a private bucket as the default disk and a public bucket named public.
To connect to a DUST Cloud bucket from outside DUST Cloud, such as during local development, register a IoCloudDisk in src/config/filesystems.rs using the bucket name, endpoint, and access keys from the dashboard (omit .public_url(..) for a private bucket):
// src/config/filesystems.rsuse dust::config::filesystems::IoCloudDisk;filesystems.add_disk( "avatars", IoCloudDisk::new( "avatars", env.get::<String>("CLOUD_BUCKET_ENDPOINT").unwrap_or_default(), env.get::<String>("CLOUD_BUCKET_KEY").unwrap_or_default(), env.get::<String>("CLOUD_BUCKET_SECRET").unwrap_or_default(), ) .public_url("https://avatars.io.cloud"),);S3-compatible disks
To store files in Amazon S3 or any S3-compatible object store, enable dust-framework's s3 Cargo feature in Cargo.toml:
[dependencies]dust-framework = { version = "0.1", features = ["s3"] }Next, set the AWS_* variables in your .env file. If you omit the access key and secret, the disk falls back to the AWS SDK's default credential chain, such as an EC2 or ECS IAM role:
FILESYSTEM_DISK=s3
AWS_ACCESS_KEY_ID=your-key
AWS_SECRET_ACCESS_KEY=your-secret
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=your-bucketThe s3 disk works with any S3-compatible service, including Cloudflare R2, DigitalOcean Spaces, and MinIO. Set AWS_ENDPOINT to your provider's endpoint, and enable AWS_USE_PATH_STYLE_ENDPOINT for providers such as MinIO that require path-style URLs:
AWS_ENDPOINT=https://objects.example.com
AWS_USE_PATH_STYLE_ENDPOINT=true
AWS_URL=https://cdn.example.comAWS_URL sets the base URL for public file URLs, such as a CDN domain. Your bucket's policy controls whether files are publicly readable; dust-framework never alters object ACLs, so generating a public URL for a private bucket does not expose the file.
To configure an additional S3 bucket, add an S3Disk in src/config/filesystems.rs. You may chain credentials, endpoint, path_style, and public_url to customize the disk:
use dust::config::filesystems::S3Disk;filesystems.add_disk( "documents", S3Disk::new("acme-documents", "eu-west-1") .credentials( env.get::<String>("DOCS_AWS_ACCESS_KEY_ID").unwrap_or_default(), env.get::<String>("DOCS_AWS_SECRET_ACCESS_KEY").unwrap_or_default(), ) .endpoint("https://objects.example.com") .path_style() .public_url("https://documents.example.com"),);Read-through disks
When migrating files from one disk to another (such as moving from local storage to S3), a read-through disk lets your application stay online during the transition. Reads check the primary disk first and fall back to the secondary disk on a miss, while writes always target the primary disk:
use dust::config::filesystems::ReadThroughDisk;filesystems.add_disk("uploads", ReadThroughDisk::new("s3", "local"));By default, when a read hits the fallback disk, dust-framework copies the file to the primary disk so future reads are served from there. If that promotion copy fails, the read still succeeds unless you chain .throw_on_promotion_failure(). To disable automatic promotion altogether, chain .without_promotion().
Deleting a file removes it from both disks so stale copies cannot resurface from the fallback.
Obtaining disk instances
Top-level functions in dust::storage operate on your default disk. For example, this handler writes a CSV report to the default disk:
use dust::prelude::*;use dust::storage;pub async fn store() -> dust::Result<Redirect> { storage::put("reports/monthly.csv", "name,total\nTaylor,42\n").await?; Ok(Redirect::back())}To target a specific disk, pass its name to storage::disk, which returns a disk handle with the same methods:
storage::disk("s3")? .put("reports/monthly.csv", "name,total\nTaylor,42\n") .await?;Storage functions work anywhere your application runs, including handlers, console commands, and queued jobs. Paths are relative to the disk's root, so reports/monthly.csv on the local disk maps to storage/app/private/reports/monthly.csv. Paths starting with / or containing .. segments are rejected with storage::InvalidPath.
On-demand disks
When you need a disk that isn't defined in your configuration (such as a directory passed to a console command), build one dynamically with storage::build:
use dust::config::filesystems::LocalDisk;use dust::storage;let imports = storage::build(LocalDisk::new("/var/imports"))?;let orders = imports.get("orders.csv").await?;On-demand local disks are not registered as HTTP mounts and cannot generate URLs, though they can still serve downloads. On-demand S3 disks can generate both public and temporary URLs as usual.
Retrieving files
Use storage::get to read a file's bytes, or storage::json to deserialize a JSON file into any type implementing Deserialize:
use dust::storage;use serde::Deserialize;#[derive(Deserialize)]struct Settings { theme: String, notifications: bool,}let contents = storage::get("reports/monthly.csv").await?;let settings: Settings = storage::json("settings.json").await?;Because get and json buffer the entire file in memory, they reject files larger than 8 MiB with storage::TooLarge. For larger files, raise the limit with get_with_limit or stream the file in chunks with read_stream:
use dust::storage;use dust::stream::TryStreamExt;let contents = storage::get_with_limit("exports/orders.csv", 32 * 1024 * 1024) .await?;let mut file = storage::read_stream("exports/orders.csv").await?;while let Some(chunk) = file.stream.try_next().await? { // Process each chunk of bytes...}Check whether a file exists with storage::exists or storage::missing:
if storage::exists("reports/monthly.csv").await? { // ...}Reading a missing file returns storage::NotFound. Returning that error directly from a handler produces a 500 response, since missing internal files usually indicate a bug. When a request specifies the filename, convert NotFound into a 404:
use dust::prelude::*;use dust::storage::{self, Bytes, NotFound};pub async fn show(Params(name): Params<String>) -> dust::Result<Bytes> { match storage::get(&format!("reports/{name}")).await { Err(error) if error.is::<NotFound>() => Err(dust::abort(404)), contents => contents, }}Downloading files
Return storage::download from a handler to prompt the browser to save a file. By default, the browser uses the path's filename; chain .name(..) to customize it. To display a file inline in the browser (such as a PDF or image), use storage::response instead. Both return 404 if the file does not exist:
use dust::prelude::*;use dust::storage::{self, FileResponse};use crate::models::User;pub async fn invoice( user: Authenticated<User>, Params(id): Params<u64>,) -> dust::Result<FileResponse> { // Verify that the user is authorized to view this invoice... Ok(storage::download(&format!("invoices/{id}.pdf"))?.name("Invoice.pdf"))}Because downloads pass through your handler, you can authorize every request. Use download for private files such as invoices rather than exposing a public URL.
File URLs
Call url to get a file's public URL on the public disk, a custom local disk marked with .public(), a public DUST Cloud bucket, or an S3 disk:
use dust::storage;let url = storage::disk("public")?.url("avatars/1.png").await?;On the public disk, this returns https://example.com/storage/avatars/1.png. On a public DUST Cloud bucket, it returns a URL under the bucket's public domain. On an S3 disk, it uses AWS_URL if configured, or the bucket's URL otherwise.
Temporary URLs
To grant time-limited access to a private file, generate a signed temporary URL:
use dust::prelude::*;use dust::storage;let url = storage::temporary_url("invoices/1.pdf", 5.minutes()).await?;On a local disk, dust-framework signs the URL with APP_KEY and serves it from the disk's mount. On S3 and DUST Cloud, the presigned URL directs the browser straight to your bucket.
You can also let browsers upload directly to a disk (avoiding routing large files like videos through your application server on S3 or DUST Cloud) using temporary_upload_url, which returns the signed URL, HTTP method, and required headers:
let upload = storage::temporary_upload_url("incoming/video.mp4", 5.minutes()).await?;// Send upload.url, upload.method, and upload.headers to the browser...File metadata
Use size, last_modified, and mime_type to inspect individual attributes, or metadata to retrieve all three in one call:
use dust::storage;let bytes = storage::size("reports/monthly.csv").await?;let modified = storage::last_modified("reports/monthly.csv").await?;let mime_type = storage::mime_type("reports/monthly.csv").await?;let metadata = storage::metadata("reports/monthly.csv").await?;let size = metadata.size;let content_type = metadata.content_type;let last_modified = metadata.last_modified;Because MIME types are inferred from the filename or reported by the storage backend rather than inspecting file bytes, do not rely on mime_type for security validation.
Storing files
Use storage::put to write a file, replacing any existing file at that path. It accepts owned or borrowed strings and byte slices. For example, this stores a CSV string and an avatar fetched via the HTTP client:
use dust::http::client;use dust::storage;storage::put("reports/monthly.csv", "name,total\nTaylor,42\n").await?;let avatar = client::get("https://example.com/avatars/taylor.png") .ensure_successful() .await?;storage::put("avatars/1.png", avatar.bytes()).await?;Streaming large files
put holds the full file in memory. For large files such as videos or database exports, use write_stream to stream chunks directly to storage as they arrive:
use dust::http::client;use dust::storage;let export = client::get("https://partner.example.com/exports/orders.csv") .stream() .await?;storage::disk("s3")? .write_stream("exports/orders.csv", export.chunks()) .await?;To stream a file out of storage in chunks, call read_stream. Its stream field yields the file's bytes, which you can pipe directly into write_stream on another disk.
Copying and moving files
Use copy and move_to to copy or move files within a single disk, or copy_to_disk and move_to_disk to transfer files across disks (copy_to_disk_as and move_to_disk_as store the file at a different path on the destination disk):
use dust::storage;storage::copy("reports/annual.pdf", "archive/annual.pdf").await?;let local = storage::disk("local")?;let s3 = storage::disk("s3")?;local.copy_to_disk(&s3, "reports/annual.pdf").await?;local.move_to_disk_as(&s3, "reports/annual.pdf", "archive/annual.pdf").await?;Moving a file across disks copies it first and deletes the original only if the copy succeeds.
File uploads
User uploads such as avatars and documents arrive as UploadedFile fields on a validated form. Call .store(directory) to save the file under a randomly generated filename with an extension derived from its contents. store returns the stored path so you can persist it in your database:
use dust::http::UploadedFile;use dust::prelude::*;#[dust::input]#[validate(authenticated)]pub struct UpdateAvatar { #[validate(required, image, max_kilobytes(2048))] avatar: UploadedFile,}pub async fn update(Valid(form): Valid<UpdateAvatar>) -> dust::Result<Redirect> { let path = form.avatar.store("avatars").disk("public").await?; // Save the path on the user... Ok(Redirect::back())}Omitting .disk(..) writes to your default disk. To choose the filename yourself, use store_as. For example, this handler names each avatar after the user's ID:
use dust::prelude::*;use crate::models::User;pub async fn update( user: Authenticated<User>, Valid(form): Valid<UpdateAvatar>,) -> dust::Result<Redirect> { let extension = form.avatar.extension().unwrap_or("png"); form.avatar .store_as("avatars", format!("{}.{extension}", user.id)) .disk("public") .await?; Ok(Redirect::back())}extension() inspects the file's contents rather than the client-supplied filename, so after the image validation rule passes, it is guaranteed to be a valid image extension such as png or jpg.
Never pass client_name to store_as, since users control that value and could overwrite another user's file. To learn more about inspecting uploaded files, check out the file uploads section of the requests guide.
Deleting files
Use storage::delete to remove a file. Deleting a path that does not exist succeeds without error:
use dust::storage;storage::delete("avatars/1.png").await?;Directories
Use files to list files in a directory and all_files to include files in nested subdirectories. Similarly, directories and all_directories list subdirectories and nested subdirectories. Each returns a stream of paths that you can collect with try_collect:
use dust::storage;use dust::stream::TryStreamExt;let reports: Vec<String> = storage::files("reports")?.try_collect().await?;Use make_directory to create a directory along with any missing parent directories; if the directory already exists, it succeeds without error. Use delete_directory to delete a directory along with all of its contents:
storage::make_directory("reports/2026").await?;storage::delete_directory("reports/2025").await?;Failure modes
| Symptom | Error or result | What to do |
|---|---|---|
| The file does not exist | storage::NotFound |
Return 404 when the name came from the request; otherwise treat it as a bug |
The file is larger than get allows |
storage::TooLarge |
Stream it with read_stream, or raise the limit with get_with_limit |
The path is absolute or contains .. |
storage::InvalidPath |
Build paths from trusted segments, never directly from user input |
| The disk is not configured | An error from storage::disk(name) |
Check the name and your filesystems configuration |
| A local directory is missing | An I/O error from the disk | Create it with make_directory, or let uploads create it |
| A public URL points at nothing | url returns a URL even before the file exists |
Check exists; the URL only describes where the file would live |
Deleting a missing file succeeds, and delete_directory removes everything under a directory, so keep both away from paths that include user input. When a download is private, generate a temporary URL or serve it through a handler with download, as the downloading files section shows.
Testing
Call storage::fake at the start of a test to replace any disk (including s3) with an isolated, empty temporary directory for the duration of the test:
use dust::http::client::Attachment;use dust::model::create;use dust::storage;use dust::testing::prelude::*;use app::models::User;#[dust::test]async fn users_can_upload_an_avatar(app: Application) -> dust::Result<()> { let disk = storage::fake("public")?; let user = create!(User { name: "Taylor", email: "taylor@example.com", password: "password", }) .await?; app.post("/avatar") .acting_as(&user) .attach("avatar", Attachment::from_path("tests/fixtures/avatar.png")) .await .assert_redirect(); disk.assert_exists(&format!("avatars/{}.png", user.id)).await; Ok(())}The returned fake also provides assert_missing and assert_contents for verifying file absence or exact bytes. Each test's fake is isolated to its own application, so concurrent tests never share files. You can learn more about building test requests in the testing guide.