要实现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列表给前端页面。