In this tutorial I’ll demonstrate how to handle upload with additional data fields using one of the most popular Rust web frameworks - actix-web, which has become my go-to web framework when developing in Rust.
We’ll start by creating a binary Rust package
1
cargo new doc-demo
Then under the project root, run
1
cargo add actix-web actix-multipart
With your favorite editor, open src/main.rs and copy/paste the following code
This simple web application has only one single POST endpoint that will accept
a field named file that points to a file in client’s file system
an optional field named layout, its value is defaulted to simple
By default the output will be the line count of the file being uploaded, but a characters result that represents the number of characters in the file will be added if layout is set to advanced. So for example,
1
curl http://localhost:8080/upload_stats -X POST -F 'file=@Cargo.toml'
returns something like
1
{"lines":13}
While
1
curl http://localhost:8080/upload_stats -X POST -F 'file=@Cargo.toml' -F 'layout=advanced'
might produce something like
1
{"lines":13,"characters":311}
p.s. here’s the full content of Cargo.toml
1 2 3 4 5 6 7 8 9 10 11 12 13
[package] name = "doc-demo" version = "0.1.0" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html