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

前提是你 提交于 2021-02-20 04:43:56

问题


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).


回答1:


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 );


来源:https://stackoverflow.com/questions/26343535/how-to-upload-to-imgur-api-v3-using-binary-format-of-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!