在Spring Boot中,实现文件上传功能通常需要使用Spring MVC的MultipartFile对象来接收并处理上传的文件。下面是一个简单的实现文件上传功能的示例代码:
@RestController
public class FileUploadController {
private final String UPLOAD_DIR = "uploads/";
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
try {
Path filePath = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
Files.write(filePath, file.getBytes());
return "File uploaded successfully!";
} catch (IOException e) {
return "Failed to upload file!";
}
}
}
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
</body>
</html>
通过上述步骤,你就可以实现一个简单的文件上传功能。当用户在HTML表单中选择一个文件并点击上传按钮时,文件将被传输到指定的目录中,并返回上传成功或失败的消息。你可以根据实际需求对文件上传功能进行扩展和优化。