---
url: /saas-starter/v0.10.1/guide/file-storage.md
---
# File storage

::: tip What this page covers
Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says
which options a part is for. The copy in your app's `docs/` folder has only the parts for yours.
`ApiHost` stands for your app's name.
:::

Files people upload (pictures, attachments, imports) go through one interface,
`IFileStorage` (`src/ApiHost/Storage/`). It has three implementations, and configuration chooses
one, so features don't change when you move from a single server to a cloud provider:

| `Storage:Provider` | Where files go | Suits |
|---|---|---|
| `Local` (the default) | A folder on the server (`Storage:Local:RootPath`) | One app on one server, such as the setup in `deploy/` |
| `S3` | Any store with the S3 API: AWS S3, Cloudflare R2, Backblaze B2, Wasabi, Hetzner, DigitalOcean Spaces, Scaleway, OVH, Google Cloud Storage, or self-hosted SeaweedFS, Garage, Ceph or RustFS | Files off the server, more than one instance, a CDN |
| `AzureBlob` | Azure Blob Storage | Apps on Azure |

All three are free, open-source code: AWS's SDK (Apache-2.0) for S3 and Microsoft's (MIT) for
Azure. The providers themselves charge for storage, except the self-hosted ones.

## How uploads work

Browsers upload and download directly with short-lived signed URLs, so large files never pass
through the app:

1. The browser asks one of your endpoints to upload. The endpoint checks the user may, picks the
   file's key, and returns `CreateUploadUrlAsync(key, contentType, lifetime)`: a URL and the
   headers to send.
2. The browser `PUT`s the file to that URL with those headers.
3. The browser tells your endpoint it's done. The endpoint checks the file with `GetInfoAsync`
   (size, content type) before using it, and deletes it if it doesn't qualify. S3 and Azure can't
   limit a signed upload's size, so this check is what enforces your limits.

Download a file with a URL from `CreateDownloadUrlAsync(key, fileName, lifetime)`. On every
provider the browser saves it as an attachment named `fileName` (`Content-Disposition:
attachment`, signed into the URL), so an uploaded HTML page or SVG drawing is never opened as a
page on the store's address, where it could pose as your app. An `<img>` still shows a picture
from it. Files the app writes itself (such as a resized picture) go through `SaveAsync`;
`OpenReadAsync`, `GetInfoAsync` and `DeleteAsync` do the rest.

**Todo attachments are the worked example** (`Features/Todos/TodoAttachments.cs` and
`TodoAttachmentEndpoints`, and `useAttachFile` in the client's `features/todos/todoQueries.ts`).
They add what a real feature needs around the three steps:

* **An upload token.** Step 1 returns, with the URL, the file's key, name and type encrypted with
  Data Protection, and step 3 takes it back, so the browser can't change what it's finishing or
  where it goes. It expires with the URL.
* **Limits checked twice:** the size the browser declares before the upload, and the stored size
  after it (`Attachments:MaxBytes`, 25 MB by default; `Attachments:MaxPerTodo`, 10).
* **Abandoned uploads cleaned up.** Starting an upload schedules `DeleteAttachmentIfUnused` for
  after the token expires, which deletes the file unless it was attached by then. Removing an
  attachment sends the same message, so the file goes once the change is saved.
* **Downloads by short-lived link:** the browser can't send the access token with a plain link,
  so it asks the API for a 5-minute download URL, then follows it.

Keys are paths such as `organisations/{id}/logo.webp`: segments of letters, digits, `.`, `_` and
`-`, separated by `/`. The same rules apply on every provider, so a key that works locally works in
production. Put the owner first (the user or organisation ID), and give keys an extension: local
disk has nowhere else to keep a file's content type.

```csharp
// Step 1: the browser asks to upload a report's PDF.
// (The Todo attachments show the whole flow, with its checks.)
[WolverinePost("/api/reports/{reportId}/upload")]
public static Task<SignedUpload> Post(Guid reportId, IFileStorage storage, CancellationToken cancellationToken)
    => storage.CreateUploadUrlAsync($"reports/{reportId}/{Guid.NewGuid():N}.pdf", "application/pdf", TimeSpan.FromMinutes(10), cancellationToken);
```

## Deleting an owner's files

When an owner of files is deleted (a user, an organisation, a record with attachments), delete its
files by publishing `DeleteStoredFiles` with its prefix from the handler that deletes its data.

::: info With accounts
`Pictures/PictureCleanup.cs` does this for `AccountDeleted`:

```csharp
public static ValueTask Handle(AccountDeleted message, IMessageContext context)
    => context.PublishAsync(new DeleteStoredFiles($"users/{message.UserId}/"));
```

:::

::: info Without accounts
For example, for a project whose files are under `projects/{id}/`:

```csharp
public static ValueTask Handle(ProjectDeleted message, IMessageContext context)
    => context.PublishAsync(new DeleteStoredFiles($"projects/{message.ProjectId}/"));
```

:::

Don't call `IFileStorage` in that handler. Each handler of a message runs on its own (its own
transaction and retries; `MultipleHandlerBehavior.Separated` in `Program.cs`), but a storage outage
there would still fail and repeat that feature's data clean-up with it. `DeleteStoredFiles` is
sent only once the data is deleted, and retried on its own (after 1 minute, 10 minutes, 1 hour and
6 hours) until the store answers.

For a single file that's been replaced, delete it in the background the same way, once the change
is saved, and check first that nothing uses it any more (`DeletePictureIfUnused` is an example).

## Local disk

Files go under `Storage:Local:RootPath` (`data/files` in the app's folder by default, relative to
it unless absolute, with or without a trailing `/`;
`src/ApiHost/data/files/` is in `.gitignore`). Signed URLs point at the app itself (`/api/files`), with
the key, the operation and the expiry encrypted in the URL by ASP.NET Core Data Protection.
`Storage:Local:MaxUploadBytes` (25 MB by default) caps each upload.

Downloads come from the app's own address, so a stored HTML page or SVG drawing could run scripts
as the app if a browser opened it. Besides coming as an attachment, as on every provider, each
download is sent with `Content-Security-Policy: default-src 'none'; sandbox`, so nothing in it can
run even if it's opened anyway.

In a container, put the folder on a volume, or files disappear with the container.
`deploy/docker-compose.yml` mounts the `app-files` volume at `/app/data`; back it up with the
database (see [deploy/README.md](./deploy-to-a-server.md)). Local disk only works with one instance
of the app: with more, use S3 or Azure.

## S3-compatible storage

Set these as environment variables, or in `deploy/.env` as `STORAGE_PROVIDER=S3` and the `S3_*`
values:

| Setting | Value |
|---|---|
| `Storage__Provider` | `S3` |
| `Storage__S3__ServiceUrl` | The store's endpoint. Leave empty for AWS itself |
| `Storage__S3__Region` | AWS: the bucket's region. R2: `auto`. Others: whatever they document (often `us-east-1`) |
| `Storage__S3__Bucket` | The bucket, which must already exist |
| `Storage__S3__AccessKey`, `Storage__S3__SecretKey` | An access key for the bucket. On AWS you can leave them empty to use an instance or task role |
| `Storage__S3__ForcePathStyle` | `true` for most self-hosted stores (the bucket goes in the path, not the host name) |

Some examples:

| Provider | `ServiceUrl` | `Region` |
|---|---|---|
| AWS S3 | (empty) | `eu-west-1` |
| Cloudflare R2 | `https://<account-id>.r2.cloudflarestorage.com` | `auto` |
| Backblaze B2 | `https://s3.<region>.backblazeb2.com` | `<region>`, such as `eu-central-003` |
| Hetzner | `https://<location>.your-objectstorage.com` | `<location>`, such as `fsn1` |
| Google Cloud Storage | `https://storage.googleapis.com` | `auto` |
| SeaweedFS, Garage, Ceph, RustFS | Your server, such as `https://s3.example.com` | `us-east-1` (with `ForcePathStyle=true`) |

**Google Cloud Storage** speaks the S3 API through its XML API: create an HMAC key for a service
account (Cloud Storage → Settings → Interoperability) and use it as the access key. Signed
uploads, downloads and the rest of `IFileStorage` work; some S3 features this app doesn't use
(such as multipart upload details) differ.

The app turns off the checksums that the AWS SDK adds to every request by default since 2025,
which many S3-compatible stores reject.

## Azure Blob Storage

Set these as environment variables, or in `deploy/.env` as `STORAGE_PROVIDER=AzureBlob` and the
`AZURE_STORAGE_*` values:

| Setting | Value |
|---|---|
| `Storage__Provider` | `AzureBlob` |
| `Storage__AzureBlob__ConnectionString` | The storage account's connection string, with its key (signed URLs are signed with it) |
| `Storage__AzureBlob__Container` | The container (`files` by default); created on first use |

Azure doesn't speak the S3 API, so it has its own implementation. Signed URLs are SAS URLs.

## Let browsers reach the store (CORS)

With S3 or Azure, the browser uploads straight to the store, from your app's address. The store
must allow that, or the browser blocks the upload. The app's Content-Security-Policy already
allows the store's address. Allow `PUT` and `GET` from your app's address, with any headers:

* **S3-compatible stores:** a CORS rule on the bucket, in the provider's dashboard or with
  `aws s3api put-bucket-cors --bucket <bucket> --endpoint-url <ServiceUrl> --cors-configuration '{"CORSRules":[{"AllowedOrigins":["https://app.example.com"],"AllowedMethods":["PUT","GET"],"AllowedHeaders":["*"],"MaxAgeSeconds":3600}]}'`.
* **Azure:** Storage account → Resource sharing (CORS) → Blob service, or
  `az storage cors add --services b --methods GET PUT --origins https://app.example.com --allowed-headers '*' --max-age 3600 --connection-string "<connection string>"`.

## Trying each provider locally

`docker compose --profile storage up -d` starts SeaweedFS (S3, on port 8333) and Azurite (Azure,
on port 10000). Then run the API with one of:

```bash
# S3 (SeaweedFS allows any origin, so no CORS rule is needed)
Storage__Provider=S3 Storage__S3__ServiceUrl=http://localhost:8333 Storage__S3__Bucket=files \
Storage__S3__AccessKey=dev-access-key Storage__S3__SecretKey=dev-secret-key Storage__S3__ForcePathStyle=true \
dotnet run --project src/ApiHost

# Azure (Azurite's well-known development account)
Storage__Provider=AzureBlob \
Storage__AzureBlob__ConnectionString="UseDevelopmentStorage=true" \
dotnet run --project src/ApiHost
```

For browser uploads to Azurite, add a CORS rule for `http://localhost:5173` with the `az` command
above and the same connection string.

::: info With the tests

## Tests

`tests/ApiHost.Tests/FileStorageTests.cs` runs the same tests against every provider: local disk
through the app, S3 against SeaweedFS and Azure against Azurite, each in a container. If you
write your own implementation (for example for another cloud), add a class that inherits
`FileStorageContract` and it gets the same tests.
:::
