Created
June 3, 2019 06:58
-
-
Save jsfan3/60b57e1541dbb4589b52b29b06dbda7c to your computer and use it in GitHub Desktop.
Cloudinary in Spring Boot - Three files: the main AppApplication, the Controller and the Service, by Francesco Galgani, www.informatica-libera.net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package yourpackage.app; | |
import com.cloudinary.Cloudinary; | |
import com.cloudinary.SingletonManager; | |
import com.cloudinary.utils.ObjectUtils; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
import org.springframework.scheduling.annotation.EnableScheduling; | |
@SpringBootApplication | |
@EnableScheduling | |
public class AppApplication { | |
private static final Logger logger = LoggerFactory.getLogger(AppApplication.class); | |
public static void main(String[] args) { | |
logger.info("Application started!"); | |
// Set Cloudinary instance | |
Cloudinary cloudinary = new Cloudinary(ObjectUtils.asMap( | |
"cloud_name", "xxx", // insert here you cloud name | |
"api_key", "xxx", // insert here your api code | |
"api_secret", "xxx")); // insert here your api secret | |
SingletonManager manager = new SingletonManager(); | |
manager.setCloudinary(cloudinary); | |
manager.init(); | |
SpringApplication.run(AppApplication.class, args); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package yourpackage.app.layer1controllers; | |
import cool.teammate.server.app.layer2services.CloudinaryService; | |
import cool.teammate.server.app.layer2services.UserService; | |
import cool.teammate.server.app.layerDAO.UserDAO; | |
import javax.annotation.Resource; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.core.io.ByteArrayResource; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.web.bind.annotation.GetMapping; | |
import org.springframework.web.bind.annotation.PathVariable; | |
import org.springframework.web.bind.annotation.PostMapping; | |
import org.springframework.web.bind.annotation.RequestBody; | |
import org.springframework.web.bind.annotation.RequestHeader; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RequestParam; | |
import org.springframework.web.bind.annotation.ResponseBody; | |
import org.springframework.web.bind.annotation.RestController; | |
import org.springframework.web.multipart.MultipartFile; | |
/** | |
* Controller for the Cloudinary Service | |
* | |
* @author Francesco Galgani | |
*/ | |
@RestController | |
@RequestMapping("/cloud") | |
public class CloudinaryController { | |
private final Logger logger = LoggerFactory.getLogger(this.getClass()); | |
@Autowired | |
CloudinaryService cloudinaryService; | |
/** | |
* Upload a MultipartFile to Cloudinary. | |
* | |
* @param authToken | |
* @param email | |
* @param file | |
* @return the publicId assigned to the uploaded file, or null in case of | |
* error | |
*/ | |
@PostMapping("/upload") | |
public @ResponseBody | |
String upload(@RequestHeader(value = "authToken") String authToken, @RequestHeader(value = "email") String email, @RequestParam("file") MultipartFile file) { | |
return cloudinaryService.upload(authToken, email, file); | |
} | |
/** | |
* Upload an Avatar to Cloudinary. | |
* | |
* @param authToken | |
* @param email | |
* @param isAvatarSinglePerson | |
* @param file | |
* @return the publicId assigned to the uploaded file, or null in case of | |
* error | |
*/ | |
@PostMapping("/uploadAvatar") | |
public @ResponseBody | |
String uploadAvatar(@RequestHeader(value = "authToken") String authToken, @RequestHeader(value = "email") String email, @RequestHeader(value="isAvatarSinglePerson") String isAvatarSinglePerson, @RequestParam("file") MultipartFile file) { | |
return cloudinaryService.uploadAvatar(authToken, email, isAvatarSinglePerson, file); | |
} | |
/** | |
* Download an image from the cloud, scaled and cropped the given size | |
* | |
* @param publicId of the image, returned by the upload() method | |
* @param width in px | |
* @param height in px | |
* @return | |
*/ | |
@GetMapping("/downloadImg/{publicId}/{width}/{height}") | |
public @ResponseBody | |
ResponseEntity<ByteArrayResource> downloadImg(@PathVariable String publicId, @PathVariable int width, @PathVariable int height) { | |
return cloudinaryService.downloadImg(publicId, width, height, false); | |
} | |
/** | |
* Download an rounded avatar from the cloud, scaled and cropped the given size | |
* | |
* @param authToken | |
* @param email | |
* @param publicId of the image, returned by the upload() method | |
* @param size in px | |
* @return | |
*/ | |
@GetMapping("/downloadAvatar/{publicId}/{size}") | |
public @ResponseBody | |
ResponseEntity<ByteArrayResource> downloadAvatar(@PathVariable String publicId, @PathVariable int size) { | |
return cloudinaryService.downloadImg(publicId, size, size, true); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package yourpackage.app.layer2services; | |
import com.cloudinary.*; | |
import com.cloudinary.utils.ObjectUtils; | |
import cool.teammate.server.app.layer3entities.User; | |
import cool.teammate.server.app.layer3entities.UserRepository; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.URL; | |
import java.net.URLConnection; | |
import java.util.Map; | |
import javax.annotation.Resource; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.core.io.ByteArrayResource; | |
import org.springframework.http.HttpHeaders; | |
import org.springframework.http.MediaType; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.stereotype.Service; | |
import org.springframework.web.multipart.MultipartFile; | |
/** | |
* Documentation: https://cloudinary.com/documentation/java_integration - | |
* https://cloudinary.com/documentation/image_transformations | |
* | |
* @author Francesco Galgani | |
*/ | |
@Service | |
public class CloudinaryService { | |
private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); | |
private final Cloudinary cloudinary = Singleton.getCloudinary(); | |
@Autowired | |
UserService userService; | |
@Autowired | |
private UserRepository userRepository; | |
/** | |
* Upload a MultipartFile to Cloudinary. More info: | |
* https://stackoverflow.com/a/39572293 | |
* | |
* @param authToken | |
* @param email | |
* @param file to be uploaded | |
* @return the publicId assigned to the uploaded file, or null in case of | |
* error | |
*/ | |
public String upload(String authToken, String email, MultipartFile file) { | |
logger.trace("Called CloudinaryService.upload with args: " + authToken + ", " + email + " and the multipart file"); | |
User user = userService.getUser(authToken, email); | |
if (user != null) { | |
try { | |
Map uploadResult = cloudinary.uploader().upload(file.getBytes(), ObjectUtils.emptyMap()); | |
String publicId = uploadResult.get("public_id").toString(); | |
logger.info("The user " + email + " successfully uploaded the file: " + publicId); | |
return publicId; | |
} catch (Exception ex) { | |
logger.error("The user " + email + " failed to load to Cloudinary the image file: " + file.getName()); | |
logger.error(ex.getMessage()); | |
return null; | |
} | |
} else { | |
logger.error("Error: a not authenticated user tried to upload a file (email: " + email + ", authToken: " + authToken + ")"); | |
return null; | |
} | |
} | |
/** | |
* Upload an avatar and save its publicID in the User entity | |
* | |
* @param authToken | |
* @param email | |
* @param isAvatarSinglePerson | |
* @param file to be uploaded | |
* @return the publicId assigned to the uploaded file, or null in case of | |
* error | |
*/ | |
public String uploadAvatar(String authToken, String email, String isAvatarSinglePerson, MultipartFile file) { | |
User user = userService.getUser(authToken, email); | |
if (user != null) { | |
String publicId = upload(authToken, email, file); | |
if ("true".equalsIgnoreCase(isAvatarSinglePerson)) { | |
user.setAvatar_SinglePerson_PublicID(publicId); | |
} else { | |
user.setAvatar_Collective_PublicID(publicId); | |
} | |
userRepository.save(user); | |
logger.info("Saved the new avatar for the user: " + email); | |
return publicId; | |
} else { | |
logger.warn("Cannot authenticate the user " + email + " to upload him/her avatar"); | |
return null; | |
} | |
} | |
/** | |
* Download an image from Cloudinary | |
* | |
* @param publicId of the image | |
* @param width | |
* @param isAvatar | |
* @param height | |
* @return | |
*/ | |
public ResponseEntity<ByteArrayResource> downloadImg(String publicId, int width, int height, boolean isAvatar) { | |
logger.info("Requested to download the image file: " + publicId); | |
// Generates the URL | |
String format = "jpg"; | |
Transformation transformation = new Transformation().width(width).height(height).crop("fill"); | |
if (isAvatar) { | |
// transformation = transformation.gravity("face").radius("max"); | |
transformation = transformation.radius("max"); | |
format = "png"; | |
} | |
String cloudUrl = cloudinary.url().secure(true).format(format) | |
.transformation(transformation) | |
.publicId(publicId) | |
.generate(); | |
logger.debug("Generated URL of the image to be downloaded: " + cloudUrl); | |
try { | |
// Get a ByteArrayResource from the URL | |
URL url = new URL(cloudUrl); | |
InputStream inputStream = url.openStream(); | |
byte[] out = org.apache.commons.io.IOUtils.toByteArray(inputStream); | |
ByteArrayResource resource = new ByteArrayResource(out); | |
// Creates the headers | |
HttpHeaders responseHeaders = new HttpHeaders(); | |
responseHeaders.add("content-disposition", "attachment; filename=image.jpg"); | |
responseHeaders.add("Content-Type", "image/jpeg"); | |
return ResponseEntity.ok() | |
.headers(responseHeaders) | |
.contentLength(out.length) | |
// .contentType(MediaType.parseMediaType(mimeType)) | |
.body(resource); | |
} catch (Exception ex) { | |
logger.error("FAILED to download the file: " + publicId); | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Documentation: https://cloudinary.com/documentation/java_integration - https://cloudinary.com/documentation/image_transformations