Thursday, April 16, 2015

Android: Upload Image + Form Parameters to PHP Server (multipart/form-data)

In any applications if you are working with a client server application, there is a high probability of syncing the images with some parameters to the server.

We have seen lot of examples to sync the text or parameters to the server and also the image or audio or video or any files to the server. You see these examples separately to send these data. But not the combined data to the server.

Now, in this blog we are going to learn how we are going to send the image and some parameters together to the server. Here the client is an android application and the server is apache with php and mysql (database).

We can consider the example of a register screen in the android application. Here I am not going to talk about the server set up, PHP and mysql configuration. It is assumed that the server setup and the PHP/Mysql configuration is done, up and running. Data base related to the registration parameters also ready. I am going to consider the First Name, Last Name, Address, Mobile Number, Email, Gender and image of the candidate to be registered.

These data is captured from the mobile and sent to the server via PHP web service. Here I am discuss about the code written from the client side. I am going to write that in a method "postdata". It is assumed that we know the web service URL of the server to send the data.

define:

public final String Web_URL = "http://xxxx.com/xxxx_reg.php";

Example client-side method (original example)

The following is the client-side method as used in this example. It demonstrates creating a multipart request containing one file and several text form fields, sending it to the server and reading the server response.

@Override
public String postdata() {
    // Create a new HttpClient and Post Header
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Web_URL);
        HttpContext localContext = new BasicHttpContext();

        /* Create a object for Mutipart Entity to send the data together */
        MultipartEntity multipartEntity = new MultipartEntity();
        String path = "image_path"; // user has to enter his image path where the captured image is stored
        File sourceFile = new File(path);
        FileBody bin1 = new FileBody(sourceFile);

        multipartEntity.addPart("uploaded_file", bin1);
        multipartEntity.addPart("fName", "Jose");
        multipartEntity.addPart("lName", "Pareria");
        multipartEntity.addPart("address", "#999, 2nd Main, 10th Block, Koramangala, Bangalore-10");
        multipartEntity.addPart("mobile", "+919999999999");
        multipartEntity.addPart("email", "abc@xyz.com");
        multipartEntity.addPart("gender", "Male");

        // Setting the Entity and executing
        httppost.setEntity(multipartEntity);
        HttpResponse response = httpclient.execute(httppost, localContext);

        // Getting the Response from the server
        BufferedReader reader = new BufferedReader(new InputStreamReader(
            response.getEntity().getContent(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null;) {
            builder.append(line).append("\n");
        }
        String getData = builder.toString();
        System.out.println(" data  " + getData);

    } catch (ClientProtocolException e) {
        Log.w("Network Error", e.toString());
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.w("IO Exception", e.toString());
    }
    return "";
}

How it works

  • The client prepares a multipart/form-data POST request. One part is a file part named "uploaded_file" containing the image file. The other parts are text form fields (fName, lName, address, mobile, email, gender).
  • The request is sent to the PHP endpoint (WebURL). The server-side script should read the file from $FILES['uploadedfile'] and the parameters from $POST.
  • The client reads the server response stream and prints it to system output.

Important implementation notes and what the code does NOT cover

  • Field names used in the request: uploaded_file, fName, lName, address, mobile, email, gender. The server must use the same names to access values.
  • The example assumes a literal "image_path" string; in a real app replace that with the actual path returned by the camera/gallery intent or a scaled/cached file.
  • The code reads the response as UTF-8 and collects it into a string (getData).

Notes for modern Android (required updates)

This article and code were written using APIs common in older Android versions. Concretely:

  • Apache HttpClient (DefaultHttpClient, HttpPost) and org.apache.http.entity.mime.MultipartEntity are deprecated and were removed from the Android SDK in newer platform releases. If your app targets modern Android versions, this code may not compile or run.

  • Use one of these modern approaches for production apps:

  • OkHttp (okhttp3) with MultipartBody for multipart uploads.

  • Retrofit (built on OkHttp) with @Multipart and @Part annotations.

  • HttpURLConnection for a lower-level standard-library approach.

  • Additional practical requirements (add these before using this code in a real app):

  • Use HTTPS (TLS) instead of HTTP to protect credentials and files in transit.

  • Request runtime permissions (READEXTERNALSTORAGE / WRITEEXTERNALSTORAGE or use scoped storage APIs) and camera permission if capturing images.

  • Scale or compress images before upload to avoid out-of-memory errors and reduce upload time.

  • Perform network calls off the UI thread (AsyncTask is deprecated — prefer executors, Kotlin coroutines, or Retrofit callbacks).

  • Add proper error handling: check HTTP response codes, server error messages, and timeouts.

  • Sanitize and validate data on the server side; restrict accepted file types and file sizes.

Suggested server-side expectations (what PHP should handle)

  • The PHP endpoint should expect a multipart/form-data POST with these keys:

  • $FILES['uploadedfile'] — the uploaded image file

  • $POST['fName'], $POST['lName'], $POST['address'], $POST['mobile'], $POST['email'], $POST['gender'] — the text fields

  • The server should:

  • Validate the uploaded file (MIME type, extension) and size.

  • Move the uploaded file to a safe directory (moveuploadedfile).

  • Insert form fields and the saved file path into the database as needed.

  • Return a clear JSON response indicating success or failure so the client can parse it.

Troubleshooting and testing

  • To inspect what the client sends, test against a known working PHP endpoint or use an HTTP inspector (Charles/mitmproxy) with HTTPS properly configured.
  • Log server-side errors and echo JSON with error messages for easier debugging.

That's it. Try it out. Happy coding.

No comments: