import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
private String restaurantPath = "C:/uploads/restaurant";
private String reviewPath = "C:/uploads/review";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/restaurant/image/**")
.addResourceLocations("file:" + restaurantPath + "/");
registry.addResourceHandler("/review/image/**")
.addResourceLocations("file:" + reviewPath + "/");
}
}
private String uploadPath = "C:/uploads/restaurant";
public void uploadImage(Restaurant restaurant, MultipartFile image) throws IOException {
File uploadDirectory = new File(uploadPath);
if (!uploadDirectory.exists()) {
uploadDirectory.mkdirs();
}
if (image.isEmpty())
restaurant.setImage("/image/startImage.jpg");
else {
String fileExtension = StringUtils.getFilenameExtension(image.getOriginalFilename());
String fileName = restaurant.getId() + "." + fileExtension;
File dest = new File(uploadPath + File.separator + fileName);
FileCopyUtils.copy(image.getBytes(), dest);
restaurant.setImage("/restaurant/image/" + restaurant.getId() + "." + fileExtension);
}
this.restaurantRepository.save(restaurant);
}