Rust, Software Development

Rust – Upload Files in Actix-Web Sample Application

Did you not know that we can upload files in Actix-Web? Well, this post is about that. We will use the Actix-Web framework to create a simple web application that others can explore and apply in their Rust projects. This post uses IntelliJ IDEA for development and Postman for testing.

Create an Actix-Web Project

As you know, the first time we need to do is create a Rust project in IntelliJ IDEA (or via Cargo CLI). Then, we update the dependency configuration file Cargo.toml.

Dependency Configuration File – Cargo.toml

Your project name may differ from ours. We named the project actix-web-upload-file. Proceed with changing the file as follows.

In the dependencies section, we have eight crates that our project depends on. Also, a few of them turn on some features available to respective crates. If you have never used these crates before, IntelliJ will start downloading them also immediately after saving the file.

Rust Server Codes for Actix-Web –

We head now to creating the server codes. First, delete everything in the file. We are going to replace them with the following codes.

Step 1 – the use statements

Ste 2 – Create struct for File Namer

Next, we define an empty struct and implement the FilenameGenerator trait. The struct will be responsible for naming the incoming file bytes from users who upload the file.

Then, we implement the trait.

Note that we are using Uuid to generate unique file names.

Step 3 – Create The Upload Handler

Then, we implement a file upload handler function that processes the content of incoming requests from clients, e.g., web browsers. Actix-web will use this function to process the file contents when users upload files using a specific URL.

Step 4 – Create a New Main function

The main function has the following codes.

When we run the codes, it writes the following output to the console.

Upload Files in Actix-web Test

Then, we test our codes using Postman.

Ensure to use form-data.

This is the HTTP response after clicking the Send button.

The files are uploaded to [current-project-dir]/uploaded-images directory.

And those are the codes to handle upload files in Actix-Web

BASIC and Bearer Authentications (Optional)

Suppose we want to secure our application, we could use Actix-web BASIC or Bearer authentication.

Tested with Rust 1.37.0.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like