@RequestBody
是 Spring MVC 中的一個注解,用于將請求體中的數據綁定到方法參數上。在處理文件上傳時,@RequestBody
通常與 MultipartFile
類型一起使用,以便將上傳的文件數據綁定到方法參數上。
以下是一個簡單的示例,展示了如何使用 @RequestBody
處理文件上傳:
pom.xml
文件中添加以下依賴: <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
@PostMapping
注解處理文件上傳請求,并使用 @RequestBody
注解將上傳的文件數據綁定到方法參數上:import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
try {
// 處理文件上傳邏輯,例如保存文件到服務器
String fileName = file.getOriginalFilename();
file.transferTo(new File("uploads/" + fileName));
return new ResponseEntity<>("File uploaded successfully: " + fileName, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>("Failed to upload file: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
application.properties
文件中添加以下配置:spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
現在,你可以使用 @RequestBody
注解處理文件上傳請求??蛻舳丝梢酝ㄟ^發(fā)送包含文件數據的 POST 請求到 /upload
端點來上傳文件。