One can test this with postman. Select file within Body, form-data
. No form data key is required for this code.
Created
September 2, 2023 15:44
-
-
Save HuakunShen/52ce7f8e0d3ddb79325cbdfc304052c4 to your computer and use it in GitHub Desktop.
Rust actix file upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "rust_http_file_upload" | |
version = "0.1.0" | |
edition = "2021" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
actix = "0.13.1" | |
actix-multipart = "0.6.1" | |
actix-rt = "2.9.0" | |
actix-web = "4.4.0" | |
futures = "0.3.28" | |
tokio = { version = "1.32.0", features = ["full"] } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use actix_multipart::Multipart; | |
use actix_web::{get, post, web, App, Error, HttpServer, Responder, HttpResponse}; | |
use futures::{StreamExt, TryStreamExt}; | |
use std::fs; | |
use std::path::PathBuf; | |
use tokio::fs::File; | |
use tokio::io::AsyncWriteExt; | |
#[get("/")] | |
async fn hello() -> impl Responder { | |
HttpResponse::Ok().body("Hello world!") | |
} | |
#[post("/upload")] | |
async fn upload_file(mut payload: Multipart) -> Result<web::Json<String>, Error> { | |
// Define the directory where uploaded files will be saved. | |
let upload_dir = "uploads/"; | |
fs::create_dir_all(upload_dir).unwrap_or_else(|_| ()); | |
while let Some(mut field) = payload.try_next().await? { | |
let content_type = field.content_disposition(); | |
// let content_type = field.content_disposition().unwrap(); | |
let filename = content_type.get_filename().unwrap(); | |
let filepath = PathBuf::from(upload_dir).join(filename); | |
let mut file = File::create(filepath).await?; | |
// Read and save the file content. | |
while let Some(chunk) = field.next().await { | |
let data = chunk?; | |
file.write_all(&data).await?; | |
} | |
} | |
Ok(web::Json("File uploaded successfully".to_string())) | |
} | |
#[actix_rt::main] | |
async fn main() -> std::io::Result<()> { | |
HttpServer::new(|| App::new().service(hello).service(upload_file)) | |
.bind("127.0.0.1:8080")? | |
.run() | |
.await | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment