Created
April 12, 2023 10:29
-
-
Save vsilent/3625dad054abe4e0dd16d4f4dc9a4481 to your computer and use it in GitHub Desktop.
Upload function with error
This file contains hidden or 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
async fn upload(form: FormData) -> Result<impl Reply, Rejection> { | |
let parts: Vec<Part> = form.try_collect().await.map_err(|e| { | |
eprintln!("form error: {}", e); | |
warp::reject::reject() | |
})?; | |
let mut response = HashMap::new(); | |
for p in parts { | |
if p.name() == "file" { | |
let content_type = p.content_type(); | |
// eprintln!("Content-Type is: {:?}", content_type); | |
let file_ending; | |
match content_type { | |
Some(file_type) => match file_type { | |
"application/pdf" => { | |
file_ending = "pdf"; | |
} | |
"image/svg+xml" => { | |
file_ending = "svg"; | |
} | |
"image/png" => { | |
file_ending = "png"; | |
} | |
"image/jpg" => { | |
file_ending = "jpg"; | |
} | |
"image/jpeg" => { | |
file_ending = "jpg"; | |
} | |
"image/gif" => { | |
file_ending = "gif"; | |
} | |
v => { | |
eprintln!("invalid file type found: {}", v); | |
return Err(warp::reject::reject()); | |
} | |
}, | |
None => { | |
eprintln!("file type could not be determined"); | |
return Err(warp::reject::reject()); | |
} | |
} | |
let value = p.stream().try_fold(Vec::new(), |mut vec, data| { | |
vec.put(data); | |
async move { Ok(vec) } | |
}) | |
.await | |
.map_err(|e| { | |
eprintln!("reading file error: {}", e); | |
warp::reject::reject() | |
})?; | |
let file_name = format!("{}.{}", Uuid::new_v4().to_string(), file_ending); | |
let file_path = format!("./files/{}", file_name); | |
tokio::fs::write(&file_path, value).await.map_err(|e| { | |
eprint!("error writing file: {}", e); | |
warp::reject::reject() | |
})?; | |
println!("created file: {}", &file_path); | |
response.insert("filename", file_name); | |
} | |
} | |
response.insert("status", StatusCode::OK.to_string()); | |
Ok(warp::reply::json(&response)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment