1. 创建文件上传接口
首先,定义一个Controller类来处理文件上传请求。
package com.example.demo.controller;
import com.example.demo.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/files")
public class FileUploadController {
@Autowired
private FileStorageService fileStorageService;
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
String fileUrl = fileStorageService.storeFile(file);
return ResponseEntity.status(HttpStatus.CREATED).body(fileUrl);
}
}
2. 创建文件存储服务
文件存储服务负责将上传的文件保存到指定的目录,并生成访问文件的URL。
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
@Service
public class FileStorageService {
@Value("${file.storage.path}")
private String storagePath;
@Value("${file.access.url}")
private String fileAccessUrl;
public String storeFile(MultipartFile file) {
// 生成唯一文件名
String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
Path filePath = Paths.get(storagePath, fileName);
try {
// 确保目录存在
Files.createDirectories(filePath.getParent());
// 保存文件
Files.copy(file.getInputStream(), filePath);
} catch (IOException e) {
throw new RuntimeException("Could not store file " + fileName, e);
}
// 返回文件的访问URL
return fileAccessUrl + "/" + fileName;
}
}
3. 配置文件
在application.properties
中配置文件存储路径和访问URL。
# 文件存储路径
file.storage.path=./uploaded-files
# 文件访问URL
file.access.url=http://localhost:8080/files
4. 配置文件上传限制
可以通过Spring Boot的配置文件来限制上传文件的大小,确保系统的安全和稳定性。
# 单个文件最大大小
spring.servlet.multipart.max-file-size=10MB
# 请求总大小限制
spring.servlet.multipart.max-request-size=20MB
5. 创建文件访问控制
如果需要控制对文件的访问权限,可以在Controller中添加相应的权限检查逻辑。
@GetMapping("/download/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
Path filePath = Paths.get(storagePath, fileName);
Resource resource = new FileSystemResource(filePath.toFile());
if (!resource.exists()) {
throw new ResourceNotFoundException("File not found: " + fileName);
}
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
6. 异常处理
为文件上传过程中的异常情况提供适当的处理。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("File upload failed: " + ex.getMessage());
}
}