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
1 | use serde::Serialize; |
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 tosimple
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 | [package] |