Upload image from Android app to server using PHP without any library

Image uploading is necessary in any Android app now a days.
We can upload image to our server from the Android app. Here I used PHP at the server side to catch and save the image file.

Here we did it without using any kind of external library. So you can directly use it in your project without any hassle.

First we pick the image from the gallery. You can checkout my article, “Pick image from gallery before and after KITKAT version in Android” and get the path of the image file in the “path” variable.

Then use following code snippet to upload that image to the server.

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
  connectURL = new URL("http://example.com/imageupload.php");
  HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
  conn.setDoInput(true);
  conn.setDoOutput(true);
  conn.setUseCaches(false);
  conn.setRequestMethod("POST");
  conn.setRequestProperty("Connection", "Keep-Alive");
  conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

  DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
  dos.writeBytes(twoHyphens + boundary + lineEnd);

  HashMap<String, String> params = new HashMap<>();
  params.put("key", "value");	//post params that you want yo send
  StringBuilder result = new StringBuilder();
  for (Map.Entry<String, String> entry : params.entrySet()) {
    result.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + lineEnd);
    result.append(lineEnd);
    result.append(entry.getValue());
    result.append(lineEnd);
    result.append(twoHyphens + boundary + lineEnd);
  }

  dos.writeBytes(result.toString());
  if (!String.valueOf("").equals(path)) {
    dos.writeBytes("Content-Disposition: form-data; name=\"" + "picture" + "\";filename=\"" + "picture.jpg" + "\"" + lineEnd);
    dos.writeBytes(lineEnd);
    fis = new FileInputStream(path);
    int bytesAvailable = fis.available();

    int maxBufferSize = 8192;
    int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    byte[] buffer = new byte[bufferSize];

    int bytesRead = fis.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
      dos.write(buffer, 0, bufferSize);
      bytesAvailable = fis.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      bytesRead = fis.read(buffer, 0, bufferSize);
    }
    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + lineEnd);
    fis.close();
  }
  dos.flush();

  InputStream is = conn.getInputStream();

  int ch;

  StringBuffer b = new StringBuffer();
  while ((ch = is.read()) != -1) {
    b.append((char) ch);
  }
  json = b.toString();
  dos.close();
} catch (MalformedURLException ex) {
} catch (IOException ioe) {
}

Make sure that you call this code snippet inside of AsyncTask or Thread. Once you get the response from the server, your image has been uploaded to the server.

Now here is the code for PHP to move the uploaded to the same directory as php file.

    move_uploaded_file($_FILES['picture']['tmp_name'], $_FILES['picture']['name']);

And done! You can find your uploaded image in “images” directory on your server.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s