问题
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