在Spring Boot中上傳文件到服務器可以通過以下步驟實現:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
// 處理文件上傳邏輯
return "File uploaded successfully";
}
}
# 文件上傳路徑
spring.servlet.multipart.location=your_file_upload_directory
# 文件最大大小
spring.servlet.multipart.max-file-size=10MB
# 請求最大大小
spring.servlet.multipart.max-request-size=10MB
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h2>File Upload</h2>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required/>
<br/><br/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
注意:在上述代碼中,your_file_upload_directory
需要替換為實際的文件上傳路徑。另外,還可以根據具體需求對文件上傳邏輯進行進一步的處理,例如保存文件、返回上傳成功的消息等。