要實現Spring Boot的批量上傳圖片功能,可以按照以下步驟進行操作:
@RestController
public class ImageUploadController {
@Autowired
private ImageStorageService imageStorageService;
@PostMapping("/uploadImages")
public List<String> uploadImages(@RequestParam("images") MultipartFile[] images) {
List<String> imageUrls = new ArrayList<>();
for (MultipartFile image : images) {
String imageUrl = imageStorageService.storeImage(image);
imageUrls.add(imageUrl);
}
return imageUrls;
}
}
public interface ImageStorageService {
String storeImage(MultipartFile image);
}
@Service
public class ImageStorageServiceImpl implements ImageStorageService {
@Value("${image.upload.directory}")
private String uploadDirectory;
@Override
public String storeImage(MultipartFile image) {
String fileName = StringUtils.cleanPath(image.getOriginalFilename());
try {
Path filePath = Paths.get(uploadDirectory, fileName);
Files.copy(image.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException e) {
throw new RuntimeException("Failed to store image " + fileName, e);
}
}
}
image.upload.directory=/path/to/upload/directory
<form method="POST" enctype="multipart/form-data" action="/uploadImages">
<input type="file" name="images" multiple>
<input type="submit" value="Upload">
</form>
以上步驟完成后,當用戶選擇并上傳多個圖片時,后端將會逐個處理每個圖片,并將其存儲到指定目錄中。每個圖片存儲成功后,將返回圖片的URL列表給前端頁面。