rust
44 lines · 8 steps
Streaming file downloads in Axum
An Axum handler that safely serves a file from disk as a streamed HTTP response with proper headers.
Explained by
highlit
1use axum::{
2 body::Body,
3 extract::Path,
4 http::{header, StatusCode},
5 response::{IntoResponse, Response},
6};
7use tokio::fs::File;
8use tokio_util::io::ReaderStream;
9
10pub async fn download(Path(filename): Path<String>) -> Result<Response, StatusCode> {
11 if filename.contains('/') || filename.contains("..") {
12 return Err(StatusCode::BAD_REQUEST);
13 }
14
15 let path = std::path::Path::new("./storage").join(&filename);
16
17 let file = File::open(&path).await.map_err(|err| match err.kind() {
18 std::io::ErrorKind::NotFound => StatusCode::NOT_FOUND,
19 _ => StatusCode::INTERNAL_SERVER_ERROR,
20 })?;
21
22 let content_length = file
23 .metadata()
24 .await
25 .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
26 .len();
27
28 let stream = ReaderStream::new(file);
29 let body = Body::from_stream(stream);
30
31 let content_type = mime_guess::from_path(&path)
32 .first_or_octet_stream()
33 .to_string();
34
35 let disposition = format!("attachment; filename=\"{filename}\"");
36
37 Ok(Response::builder()
38 .header(header::CONTENT_TYPE, content_type)
39 .header(header::CONTENT_LENGTH, content_length)
40 .header(header::CONTENT_DISPOSITION, disposition)
41 .body(body)
42 .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
43 .into_response())
44}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Validate user-supplied filenames before touching the filesystem to block path-traversal attacks.
- 2Streaming a file with ReaderStream avoids loading the whole thing into memory.
- 3Mapping each error kind to a status code gives clients meaningful failure responses.
Related explainers
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/streaming-file-downloads-in-axum-explained-rust-d8d9/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.