springboot

springboot批量上传图片怎么实现

小亿
165
2023-11-23 04:25:05
栏目: 编程语言

要实现Spring Boot的批量上传图片功能,可以按照以下步骤进行操作:

  1. 首先,创建一个Controller类,用于处理上传图片的请求和逻辑:
@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;
  }
}
  1. 创建一个ImageStorageService接口和实现类,用于存储图片:
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);
    }
  }
}
  1. 在application.properties文件中配置图片上传的目录:
image.upload.directory=/path/to/upload/directory
  1. 在前端页面中创建一个表单,用于批量上传图片:
<form method="POST" enctype="multipart/form-data" action="/uploadImages">
  <input type="file" name="images" multiple>
  <input type="submit" value="Upload">
</form>

以上步骤完成后,当用户选择并上传多个图片时,后端将会逐个处理每个图片,并将其存储到指定目录中。每个图片存储成功后,将返回图片的URL列表给前端页面。

0
看了该问题的人还看了