下面是Spring Boot项目中实现文件上传功能的完整攻略。
1. 添加依赖
在pom.xml文件中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2. 配置上传文件的路径
在application.properties文件中添加如下配置:
# 文件上传路径
file.upload-dir=/tmp/upload-dir/
3. 编写控制器
@RestController
public class FileUploadController {
@Autowired
private FileUploadService fileUploadService;
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
fileUploadService.uploadFile(file);
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
return ResponseEntity.ok("File uploaded successfully");
}
}
4. 编写Service
@Service
public class FileUploadService {
@Value("${file.upload-dir}")
private String uploadDir;
public void uploadFile(MultipartFile file) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
Files.copy(file.getInputStream(), uploadPath.resolve(file.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
}
}
在Service中读取application.properties中上传文件的目标路径,并使用Files.copy()方法将上传文件复制到对应目录中。
5. 编写HTML页面
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>File Upload Example</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>
示例1:上传单个文件
在HTML页面上添加一个表单,用户可以通过该表单提交文件上传请求。在控制器中使用@RequestParam注解,获取客户端传输过来的MultipartFile类型的文件。
示例2:上传多个文件
在HTML页面上添加如下代码,可以上传多个文件:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>File Upload Example</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" id="file" multiple />
<button type="submit">Upload</button>
</form>
</body>
</html>
控制器修改如下:
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile[] files) {
try {
for (MultipartFile file : files) {
fileUploadService.uploadFile(file);
}
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
return ResponseEntity.ok("Files uploaded successfully");
}
可以通过使用@RequestParam注解,将MultipartFile数组作为参数来简单地实现上传多个文件的功能。
以上就是Spring Boot实现文件上传功能的完整攻略,希望可以帮助到你。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Spring Boot项目中实现文件上传功能的示例 - Python技术站