Rico's Blog

Back

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

cargo new doc-demo
bash

Then under the project root, run

cargo add actix-web actix-multipart
bash

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

  1. a field named file that points to a file in client’s file system
  2. 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,

curl http://localhost:8080/upload_stats -X POST -F 'file=@Cargo.toml'
bash

returns something like

{"lines": 13}
json

While

curl http://localhost:8080/upload_stats -X POST -F 'file=@Cargo.toml' -F 'layout=advanced'
bash

might produce something like

{"lines": 13, "characters": 311}
json

p.s. here’s the full content of Cargo.toml

[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

[dependencies]
actix-multipart = "0.4.0"
actix-web = "4.1.0"
futures-util = "0.3.21"
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.81"
toml