Skip to main content

Storing files in a remote location - Cloudinary

When you are developing an application or a website, you may use a file storage to store certain resources such as images, videos etc. 

If you specify a particular image location in your code and later if you change this location, you might have to find all its usages and refactor. If you store the image in a remote location and retrieve it using the URL, this problem can be avoided.

There can be certain services (eg: Image Processing, Image Understanding etc.) that require Image URLs to be given. 

So rather than maintaining our service, we can use the service provided by Cloudinary[1]. I found this service to be very reliable and very well documented. You can use their API or SDK to consume their service. In order to do so you must first create an account. A free account will support upto 75000 uploads.

This blog post will contain a Java Source code that consumes their service through the API.


Step 1: Register


After registering with their service, you will be redirected to the following dashboard.






Step 2: Code Image Uploader Service 

This code contains two methods. One is to upload the image, the other one is to bulk delete.

Second method is there to show how to make authorized called using Basic Authentication in Cloudinary.

All manipulations that can be carried out can be found in their documentation. [2]


 package main.java;  
 import okhttp3.*;  
 import org.apache.commons.codec.binary.Base64;  
 import org.apache.commons.codec.digest.DigestUtils;  
 import org.json.JSONObject;  
 import java.io.*;  
 import java.sql.Timestamp;  
 /**  
  * @author Created by Dinuksha Ishwari.  
  */  

 public class ImageUploader {  
   private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpeg");  
   private static final String API_SECRET = "your_api_secret";  
   private static final String API_KEY = "your_api_key";  
   private OkHttpClient client = new OkHttpClient();  
   private static final String CLOUD_NAME = "your_cloud_name";  
   private static final String URL = "https://api.cloudinary.com/v1_1/"+CLOUD_NAME+"/image/upload";  
   private static final String DELETE_URL = "https://api.cloudinary.com/v1_1/"+CLOUD_NAME+"/resources/image/upload?all=true";  
   private static final byte[] encoded = Base64.encodeBase64((API_KEY+":"+API_SECRET).getBytes());  
   private static final String credentials = new String(encoded); 
 
    /**
     * Uploads an image to Cloudinary store
     * @param img - as a byte array
     * @return url of the image
     * @throws IOException
     */ 
   public String uploadImage(byte[] img) throws IOException {  
     String timestamp = Long.toString(new Timestamp(System.currentTimeMillis()).getTime());  
     String signature = "timestamp="+timestamp+API_SECRET;  
     String sha1password = DigestUtils.sha1Hex(signature);  
     RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)  
                                 .addFormDataPart("file","temp", RequestBody.create(MEDIA_TYPE_PNG, img))  
                                 .addFormDataPart("api_key",API_KEY)  
                                 .addFormDataPart("timestamp",timestamp)  
                                 .addFormDataPart("signature",sha1password)  
                                 .build();  

     Request request = new Request.Builder().url(URL).post(requestBody).build();  
     Response response = client.newCall(request).execute();  
     JSONObject obj = new JSONObject(response.body().string());  
     String imgUrl = obj.getString("url");  
     return imgUrl;  
   }  

    /**
     * Deletes all the images in the storage
     * @return response
     * @throws IOException
     */
   public String bulkDelete() throws IOException {  
     Request request = new Request.Builder().url(DELETE_URL).header("Authorization","Basic "+credentials).delete().build();  
     Response response = client.newCall(request).execute();  
     return response.body().string();  
   }  
 }  

Comments

Popular posts from this blog

Fixing 'java RMI - ConnectException: Operation timed out' in WSO2 Enterprise Integrator 6.4

If you ever come across the below exception when running WSO2 Enterprise Integrator 6.4, here is the fix. This error occurs when you have multiple IP addresses from different networks configured in your etc/hosts as below. 10.xxx.x.xxx localhost 192.xxx.x.xxx localhost So simply, removing the unnecessary one and leaving the one of the network that you are currently connected to should resolve this issue. 10.xxx.x.xxx localhost

Student Information System - Java (SLIIT - ST2 PROJECT)

Student Information System (Github Project) This system is developed in Java and mySQL as a group project by me and 3 other members during a period of 1 month. The system allows the administrator to,  enroll students to the system  update enroll information  add/update course and degree program details  generate reports  create exams and edit relevant information  calculate gpa of the relevant exam  assign lecturers to courses  add lecturers/update details Lecturers to,  assign course grades  view their feedback  generate reports  view student / course / degree program details Students to,  view their profile  view their grading information  give feedback to lecturers   view lecturer / course / degree program details and other features. Below are some interfaces of the project. (Splash Screen) (Login) (Admin View) (Student Re...

SIMPLE BLACKJACK GAME IN JAVA (CONSOLE)

import java.util.Scanner; class BlackJack{     public static void main(String[] args)      {         int player_random1 = 100;         int player_random2 = 100;         while(player_random1 >= 12 || player_random2 >= 12  || player_random1 < 3 || player_random2 <3)         {             player_random1 = (int)(Math.random()*100);             player_random2 = (int)(Math.random()*100);         }                  int player_total = player_random1 + player_random2;                  System.out.println("You get a "+player_random1+" and a "+player_random2);         System.out.println("Your total is "+player_total); if(player_total==21)  ...