File Storage
- Introduction
- Complete Example: Store and Read a File
- Configuration
- Obtaining Disk Instances
- Retrieving Files
- Storing Files
- Deleting Files
- Directories
- Testing
Introduction
The Storage facade gives one API for files on the local disk and on Amazon S3 (or an S3-compatible service such as MinIO), like Laravel's Storage facade. Disks are configured in config/Filesystems.cs.
Configuration
public class FilesystemsConfig : ConfigFile
{
public override object Values() => new
{
@default = "local",
disks = new
{
local = new { driver = "local", root = "storage/app/private" },
@public = new { driver = "local", root = "storage/app/public", url = "/storage" },
s3 = new
{
driver = "s3",
key = Env("AWS_ACCESS_KEY_ID"),
secret = Env("AWS_SECRET_ACCESS_KEY"),
region = "us-east-1",
bucket = Env("AWS_BUCKET"),
endpoint = Env("AWS_ENDPOINT"),
use_path_style_endpoint = false,
},
},
};
}default names the disk used by the Storage facade's own methods (default local). Env("NAME") reads a value from environment variables or .env (see configuration).
The Local Driver
A local disk stores files under its root. Relative roots are resolved against the application's content root. If local or public is missing from the configuration, it still works with these defaults:
| Disk | Default root | Default URL |
|---|---|---|
local | storage/app/private | none (private) |
public | storage/app/public | /storage |
Paths are always relative to the disk root. A path that would escape it, such as ../outside.txt or notes/../../secret, throws an UnauthorizedAccessException.
The Public Disk
Files on the public disk are meant to be publicly accessible. DotBlaze serves the public disk's root as static files at the disk's url (default /storage), so there is no storage:link step:
await Storage.Disk("public").Put("avatars/1.jpg", bytes);
Storage.Disk("public").Url("avatars/1.jpg"); // "/storage/avatars/1.jpg"NOTE
The files are served only when the public disk uses the local driver and its url is a relative path such as /storage. An absolute url (for example a CDN) is not served by the application; it is only used to build URLs.
Amazon S3 and MinIO
The s3 driver lives in a separate package. Install it in your application; DotBlaze loads it automatically when a disk uses "driver": "s3":
dotnet add package DotBlaze.Storage.S3Without the package, using an s3 disk throws an InvalidOperationException that tells you which package to add.
| Key | Description |
|---|---|
key, secret | Access key ID and secret access key. |
bucket | Bucket name (required). A missing value, such as an unset AWS_BUCKET, throws S3 disk needs a "bucket". |
region | Region, default us-east-1. |
root | Optional key prefix; every path on the disk is stored below it. |
endpoint | Custom endpoint for MinIO or another S3-compatible service. Leave empty for AWS. |
use_path_style_endpoint | true for path-style URLs (endpoint/bucket/key), which MinIO needs. Default false. |
url | Optional public base URL (for example a CDN) used by Url(). |
A MinIO disk for local development, in disks:
minio = new
{
driver = "s3",
endpoint = "http://localhost:9000",
key = "minioadmin",
secret = "minioadmin",
bucket = "dotblaze",
use_path_style_endpoint = true,
},Obtaining Disk Instances
The Storage facade's methods use the default disk. Storage.Disk(name) returns another disk as an IFilesystem:
await Storage.Put("notes/a.txt", "hello"); // default disk
await Storage.Disk("s3").Put("avatars/1.jpg", stream); // the s3 diskUsing a disk that is not configured throws an InvalidOperationException.
Retrieving Files
string contents = await Storage.Get("notes/a.txt"); // UTF-8 text
await using var stream = await Storage.ReadStream("notes/a.txt");
bool exists = await Storage.Exists("notes/a.txt");
long bytes = await Storage.Size("notes/a.txt");File URLs
Url(path) returns the URL of a file:
Storage.Disk("public").Url("avatars/1.jpg"); // "/storage/avatars/1.jpg"
Storage.Disk("s3").Url("avatars/1.jpg"); // "https://{bucket}.s3.{region}.amazonaws.com/avatars/1.jpg"For a local disk the url key is the base; a disk without one (such as local) is private and Url() throws an InvalidOperationException. For s3, the base is the url key if set, otherwise the endpoint (with the bucket in the path when path-style is on), otherwise the AWS bucket URL.
Temporary URLs
TemporaryUrl creates a pre-signed URL that gives access to a private file until it expires. It is only supported by the s3 driver; local disks throw a NotSupportedException:
var url = Storage.Disk("s3").TemporaryUrl("invoices/9.pdf", TimeSpan.FromMinutes(5));Storing Files
Put writes a string (as UTF-8), a byte array, or a stream, creating directories as needed and overwriting an existing file:
await Storage.Put("notes/a.txt", "hello");
await Storage.Put("exports/report.csv", stream);
await Storage.Disk("public").Put("avatars/1.jpg", new byte[] { 1, 2, 3 });NOTE
The byte-array overload is available on disks (Storage.Disk(...)), not on the Storage facade itself.
File Uploads
Uploaded files (IFormFile) have Store and StoreAs methods. Store generates a random 40-character file name and keeps the original extension only when it is short and alphanumeric, so a malicious client file name cannot influence the path. Both return the path relative to the disk:
public async Task<IActionResult> UpdateAvatar()
{
var path = await Request.File("avatar")!.Store("avatars", disk: "public");
// "avatars/Xb3k...40 chars...Q9.png"
return Back().With("avatar", Storage.Disk("public").Url(path));
}StoreAs uses the name you give it:
var path = await file.StoreAs("avatars", $"{Auth.Id()}.png", disk: "public"); // "avatars/1.png"Without disk:, the default disk is used. See retrieving uploaded files.
Deleting Files
await Storage.Delete("notes/a.txt");Directories
Files(directory) lists the files directly inside a directory (not in subdirectories), as paths relative to the disk. A missing directory gives an empty list:
IReadOnlyList<string> files = await Storage.Files("notes"); // ["notes/a.txt"]Testing
Storage.Fake(disk) swaps a disk (the default disk when no name is given) for a fresh temporary directory, and returns a FakeFilesystem with assertions:
var disk = Storage.Fake("public");
IFormFile upload = new FormFile(new MemoryStream(bytes), 0, bytes.Length, "avatar", "Me.PNG");
var path = await upload.Store("avatars", disk: "public");
disk.AssertExists(path);
disk.AssertMissing("avatars/other.png");Like the other fakes, it only affects the current test (async flow). A fake disk's Url() returns /storage/... paths. See mocking.
Complete Example: Store and Read a File
Create this Blog command; it uses a temporary fake disk, so it cannot overwrite application uploads:
// app/Commands/StorageDemo.cs
using DotBlaze;
namespace Blog.Commands;
public class StorageDemo : Command
{
public override string Signature => "demo:storage";
public override async Task<int> Handle()
{
var disk = Storage.Fake("local");
await Storage.Disk("local").Put("examples/hello.txt", "Hello from storage.");
disk.AssertExists("examples/hello.txt");
var text = await Storage.Disk("local").Get("examples/hello.txt");
if (text != "Hello from storage.")
throw new InvalidOperationException("Stored text did not round-trip.");
await Storage.Disk("local").Delete("examples/hello.txt");
disk.AssertMissing("examples/hello.txt");
Line("Stored, read, and deleted the example file.");
return 0;
}
}Run dotblaze demo:storage; expected exit code: 0. A real local disk is private, while public is served under /storage. For a complete multipart upload that validates image contents and uses a unique server-chosen filename, see Images.