Skip to content

Instantly share code, notes, and snippets.

@kjlubick
Created July 2, 2014 19:46
Show Gist options
  • Save kjlubick/70aea8d38831777360c0 to your computer and use it in GitHub Desktop.
Save kjlubick/70aea8d38831777360c0 to your computer and use it in GitHub Desktop.
Uploading images using Apache HTTPComponents (HTTPClient, MultipartEntityBuilder)
//The following is in snippet form.
//It shows 2 ways to upload files, the first is the cannonical way, if you have the image on disk
//the second is a way to upload it without having to write a modified image to disk (in this instance, a cropped image)
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
private CloseableHttpClient client = HttpClients.createDefault();
private void reportImage(File file) throws IOException
{
URI putUri;
try {
putUri = this.preparePutURI(file.getName());
} catch (URISyntaxException e){
throw new IOException("Problem making the uri to send", e);
}
HttpPut httpPut = new HttpPut(putUri);
try {
MultipartEntityBuilder mpeBuilder = MultipartEntityBuilder.create();
mpeBuilder.addBinaryBody("image", file);
HttpEntity content = mpeBuilder.build();
httpPut.setEntity(content);
client.execute(httpPut);
} finally {
httpPut.reset();
}
}
private void reportCroppedImage(File imageFile, Rectangle rect) throws IOException
{
URI putUri;
try{
putUri = this.preparePutURI(imageFile.getName());
}catch (URISyntaxException e) {
throw new IOException("Problem making the uri to send", e);
}
HttpPut httpPut = new HttpPut(putUri);
try {
MultipartEntityBuilder mpeBuilder = MultipartEntityBuilder.create();
BufferedImage image = ImageIO.read(imageFile);
BufferedImage croppedImage = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
ByteArrayOutputStream croppedJPG = new ByteArrayOutputStream();
ImageIO.write(croppedImage, PostProductionHandler.INTERMEDIATE_FILE_FORMAT, croppedJPG);
byte[] croppedJPGForTransfer = croppedJPG.toByteArray();
//the following line makes this identical to adding a file to body
mpeBuilder.addBinaryBody("image", croppedJPGForTransfer, ContentType.DEFAULT_BINARY, "file");
HttpEntity content = mpeBuilder.build();
httpPut.setEntity(content);
client.execute(httpPut);
}
finally {
httpPut.reset();
}
}
private URI preparePutURI(String reportingName) throws URISyntaxException
{
//makes a URI
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment