From 500ac029df62265c512d7d1f37db9387e7bbd46b Mon Sep 17 00:00:00 2001 From: Maxwell Jeffress Date: Mon, 25 Nov 2024 14:50:03 +1100 Subject: [PATCH] Add file upload support --- server/settings.gradle.kts | 2 +- server/src/main/kotlin/Main.kt | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/server/settings.gradle.kts b/server/settings.gradle.kts index f475a9f..5f5ab6c 100644 --- a/server/settings.gradle.kts +++ b/server/settings.gradle.kts @@ -1,5 +1,5 @@ plugins { id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" } -rootProject.name = "chookpen" +rootProject.name = "chookchat" diff --git a/server/src/main/kotlin/Main.kt b/server/src/main/kotlin/Main.kt index 382a9eb..8fc1066 100644 --- a/server/src/main/kotlin/Main.kt +++ b/server/src/main/kotlin/Main.kt @@ -2,6 +2,8 @@ package xyz.maxwellj.chookchat import io.javalin.Javalin import io.javalin.websocket.WsContext +import io.javalin.http.UploadedFile + import java.util.concurrent.ConcurrentHashMap import java.util.UUID @@ -359,6 +361,33 @@ fun main(args: Array) { ctx.redirect("/index.html") } .get("/api/createaccount/{content}") { ctx -> ctx.result(createAccount(ctx.pathParam("content")))} + .post("/api/upload") { ctx -> + val uploadedFiles = ctx.uploadedFiles() + if (uploadedFiles.isEmpty()) { + ctx.status(400).result("No files uploaded") + return@post + } + val uploadedFile = uploadedFiles[0] + val originalFilename = uploadedFile.filename() + val uuid = UUID.randomUUID().toString() + val fileExtension = originalFilename.substringAfterLast(".", "") + val baseFilename = originalFilename.substringBeforeLast(".") + val newFilename = "${baseFilename}_${uuid}${if (fileExtension.isNotEmpty()) ".$fileExtension" else ""}" + val filePath = Paths.get("uploads", newFilename) + Files.copy(uploadedFile.content(), filePath) + val processedData = JSONObject().apply { + put("type", "fileStatus") + put("username", "system") + put("content", "success") + } + ctx.result(processedData.toString()) + val processedData2 = JSONObject().apply { + put("type", "file") + put("username", "system") + put("content", "https://maxwellj.xyz/chookchat/uploads/$newFilename") + } + WsSessionManager.broadcast(processedData2.toString()) + } .ws("/api/websocket") { ws -> ws.onConnect { ctx -> WsSessionManager.addSession(ctx)