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 serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 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.