Akashic Records

Spring Boot file uploader 본문

Spring.io

Spring Boot file uploader

Andrew's Akashic Records 2020. 11. 26. 21:22
728x90

Follow these five steps to use Spring Boot to upload files from the client to the server:

  1. Create a Spring Boot application and include the Spring Web facilities;
  2. Create a Spring @Controller class;
  3. Add a method to the controller class which takes Spring’s MultipartFile as an argument;
  4. Save the uploaded file to a directory on the server; and
  5. 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