Search code examples
javaimage-uploadingbinaryfilesimgur

How to upload to Imgur (API v3) using binary format of image?


As per the API we can upload images as a binary file.

https://api.imgur.com/endpoints/image#image-upload

I tried the following to read the file into a byte array.

// Example 1
byte[] fileBytes  = new byte[(int) new File("/home/sample.png").length()];
fileBytes =  FileUtils.readFileToByteArray( this.imageRequest.getFile() );
String sImageBinaryData = new String( fileBytes );

How exactly should i extract binary data of an image?

PS: I am not interested to know how to upload image using (base64 & URL).


Solution

  • I used HttpClient/HttpMime to post the image as a binary file

    "MultipartEntity" is currently deprecated. I had to use MultipartEntityBuilder

    1) Included the following jar httpmime which is a dependent jar to HttpClient.

    2)

     MultipartEntityBuilder builder = MultipartEntityBuilder.create();
     builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    
     File file = new File("/sample.jpg");
     FileBody filebody = new FileBody(file);
     builder.addPart("image", filebody );
     builder.addTextBody("type", "file");
     builder.addTextBody("album", '<Deleted hash>' );    //anonymous album
    
     HttpEntity entity = builder.build();
    
     HttpPost httpPost = new HttpPost("<Imgur API endpoint>");
     httpPost.setEntity( entity );
    
     CloseableHttpClient httpClient = HttpClientBuilder.create().build()
     HttpResponse response = httpClient.execute( httpPost );