From 4072902ae1ba5cf5f1200c9c8a5f8016bc7e07f6 Mon Sep 17 00:00:00 2001 From: Rick <1450685+LinuxSuRen@users.noreply.github.com> Date: Thu, 3 Oct 2024 18:13:27 +0800 Subject: [PATCH] support to save the uploaded file (#29) * support to save the uploaded file * update readme --------- Co-authored-by: rick --- README.md | 5 +++++ .../github/devopsws/demo/service/FileService.java | 10 ++++++++-- .../github/devopsws/demo/service/RootService.java | 13 +++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 src/main/java/io/github/devopsws/demo/service/RootService.java diff --git a/README.md b/README.md index d5a8778..f200b1a 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,11 @@ Run with Maven command: mvn spring-boot:run ``` +Change the listen port: +```shell +java -jar demo.jar --server.port=8081 +``` + ## OpenAPI definition You can visit it via: http://localhost:8080/v3/api-docs diff --git a/src/main/java/io/github/devopsws/demo/service/FileService.java b/src/main/java/io/github/devopsws/demo/service/FileService.java index 03090f9..d3e3587 100644 --- a/src/main/java/io/github/devopsws/demo/service/FileService.java +++ b/src/main/java/io/github/devopsws/demo/service/FileService.java @@ -1,5 +1,8 @@ package io.github.devopsws.demo.service; +import java.io.FileOutputStream; + +import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -16,8 +19,11 @@ public Message upload(@RequestParam("file") MultipartFile file) { System.out.println("Received file uploading request"); Message message = new Message(); if (!file.isEmpty()) { - try { - System.out.println("Uploading file size:" + file.getSize()); + String filename = file.getOriginalFilename(); + try (FileOutputStream out = new FileOutputStream(filename)) { + System.out.println("Uploading file size: " + file.getSize() + ", name: " + filename); + + FileCopyUtils.copy(file.getInputStream(), out); message.setMessage("ok"); } catch (Exception e) { diff --git a/src/main/java/io/github/devopsws/demo/service/RootService.java b/src/main/java/io/github/devopsws/demo/service/RootService.java new file mode 100644 index 0000000..35f4927 --- /dev/null +++ b/src/main/java/io/github/devopsws/demo/service/RootService.java @@ -0,0 +1,13 @@ +package io.github.devopsws.demo.service; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController("/") +public class RootService { + + @GetMapping("") + public String index() { + return "Let's learn spring boot!"; + } +}