Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- NIO
- android
- 자바네트워크
- 파이썬
- GPT-4's answer
- 코틀린
- 자바
- 소프트웨어공학
- write by GPT-4
- Java
- kotlin
- Database
- 인프라
- oracle
- JVM
- 고전역학
- Spring boot
- python
- 웹 크롤링
- lombok
- 시스템
- 리눅스
- write by chatGPT
- 역학
- GIT
- chatGPT's answer
- 뉴턴역학
- 유닉스
- 자바암호
- flet
Archives
- Today
- Total
Akashic Records
Spring Boot file uploader 본문
728x90
Follow these five steps to use Spring Boot to upload files from the client to the server:
- Create a Spring Boot application and include the Spring Web facilities;
- Create a Spring @Controller class;
- Add a method to the controller class which takes Spring’s MultipartFile as an argument;
- Save the uploaded file to a directory on the server; and
- Send a response code to the client indicating the Spring file upload was successful.
Spring Boot file upload controller
Developers should use the following code for the controller class, which handles the Spring file upload:
import java.io.File;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class SpringFileUploadController {
@GetMapping("/index")
public String hello() {
return "uploader";
}
@PostMapping("/upload")
public ResponseEntity<?> handleFileUpload( @RequestParam("file") MultipartFile file ) {
String fileName = file.getOriginalFilename();
try {
file.transferTo( new File("C:\\upload\\" + fileName));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
return ResponseEntity.ok("File uploaded successfully.");
}
}
Ajax and Spring file uploader
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title> Ajax Spring File Upload Example </title>
</head>
<body>
<!-- HTML5 Input Form Elements -->
<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>
<!-- Ajax JavaScript File Upload to Spring Boot Logic -->
<script>
async function uploadFile() {
let formData = new FormData();
formData.append("file", fileupload.files[0]);
let response = await fetch('/upload', {
method: "POST",
body: formData
});
if (response.status == 200) {
alert("File successfully uploaded.");
}
}
</script>
</body>
</html>
728x90
'Spring.io' 카테고리의 다른 글
Spring Batch+quartz 연동 (0) | 2023.03.31 |
---|---|
Spring Boot Actuator (0) | 2023.03.23 |
Spring All Dependency Injection Types (0) | 2021.02.19 |
Spring Boot Project 만들기 (0) | 2021.01.26 |
Spring batch - ItemReaders, ItemWriters and ItemStream (0) | 2020.12.21 |
Comments