在Java Spring Boot中实现文件上传是一个常见的任务。以下是一个简单的示例,展示如何使用Spring Boot框架来构建一个RESTful API,该API允许用户上传文件到服务器。
### 1. 添加依赖
首先,在你的`pom.xml`文件中添加Spring Boot Web依赖:
<dependencies>
<!-- ... 其他依赖 ... -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
### 2. 配置文件存储属性
在`application.properties`或`application.yml`文件中,你可以配置文件存储的相关属性,例如上传文件的存放目录:
# application.properties
file.upload-dir=/path/to/upload/directory
### 3. 创建文件存储服务
创建一个服务来处理文件的保存逻辑:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@Service
public class FileStorageService {
@Value("${file.upload-dir}")
private String uploadDir;
public String storeFile(MultipartFile file) {
// 文件名处理
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
if (fileName.contains("..")) {
throw new FileStorageException("文件名不合法: " + fileName);
}
// 复制文件到指定的路径
Path targetLocation = Paths.get(uploadDir).resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException ex) {
throw new FileStorageException("无法存储文件 " + fileName + "。请重试!", ex);
}
}
}
### 4. 创建控制器
创建一个控制器来处理文件上传的HTTP请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
@RestController
@RequestMapping("/api/upload")
public class FileUploadController {
@Autowired
private FileStorageService fileStorageService;
@PostMapping("/")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
URI fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/download/")
.path(fileName)
.build()
.toUri();
return ResponseEntity.ok().body("文件上传成功: " + fileDownloadUri);
}
}
### 5. 异常处理
创建自定义异常来处理文件上传过程中可能出现的错误:
public class FileStorageException extends RuntimeException {
public FileStorageException(String message) {
super(message);
}
public FileStorageException(String message, Throwable cause) {
super(message, cause);
}
}
### 6. 测试上传
现在,你可以启动Spring Boot应用程序,并通过发送一个包含文件的POST请求到`/api/upload/`来测试文件上传功能。