How to:‎ > ‎

Upload an image to a web site

After getting a Bitmap object from the camera or some other source, it's frequently useful to upload that image to a website so it can be shared with others. This How-to will describe how to do that over HTTP.

The steps are straight forward:
  1. Create a URL to the desired path
  2. Create an HttpURLConnection from that URL, and set its parameters correctly to allow for communication in both directions
  3. Open the connection, and write the image to the request body
  4. Check for a valid response

try {
        // Step 1
URL url = new URL(HTTP_UPLOAD_PATH);

        // Step 2
HttpURLConnection c = (HttpURLConnection) url.openConnection();
            // this HTTP request will involve input
c.setDoInput(true);
            // should be PUT or POST to follow convention
c.setRequestMethod(REQUEST_METHOD);
            // this HTTP request will involve output
c.setDoOutput(true);
            // open the HTTP connection
c.connect();

        // Step 3
OutputStream output = c.getOutputStream();

            // compress and write the image to the output stream
bitmap.compress(CompressFormat.JPEG, 50, output);

output.close();

        // Step 4
Scanner result = new Scanner(c.getInputStream());
            // check for success
        String response = result.nextLine();
        if (!(SUCCESS_RESPONSE.equals(response)) {
            Log.e("ImageUploader", "Error uploading image: " + response);
        }
result.close();

} catch (IOException e) {
            // log error
Log.e("ImageUploader", "Error uploading image", e);
}

Comments