Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Added upload_image admin route for image uploads #370

Merged
merged 3 commits into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/endpoints/admin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ pub mod quest;
pub mod quest_boost;
pub mod quiz;
pub mod twitter;
pub mod upload_image;
pub mod user;
33 changes: 33 additions & 0 deletions src/endpoints/admin/upload_image.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use axum::{
extract::{Multipart, Path},
http::StatusCode,
response::IntoResponse,
};
use axum_auto_routes::route;
use std::{fs::create_dir_all, path::Path as FilePath};

#[route(post, "/admin/upload_image/:image_name")]
pub async fn upload_image_handler(
Path(image_name): Path<String>,
mut multipart: Multipart,
) -> impl IntoResponse {
let images_folder = "./images";
if !FilePath::new(images_folder).exists() {
create_dir_all(images_folder).unwrap();
}

while let Some(field) = multipart.next_field().await.unwrap() {
if let Some(filename) = field.file_name() {
if filename.ends_with(".webp") {
let filepath = format!("{}/{}.webp", images_folder, image_name);
let data = field.bytes().await.unwrap();
tokio::fs::write(filepath, data).await.unwrap();
return StatusCode::OK.into_response();
} else {
return (StatusCode::BAD_REQUEST, "Only .webp files are allowed").into_response();
}
}
}

(StatusCode::BAD_REQUEST, "No valid file provided").into_response()
}