Android Uploading a File to a PHP Server

The following script allows you to upload a file from your Android application by sending the file to the PHP server, which can then save the file to the disk.

/**
 * Upload the specified file to the PHP server.
 *
 * @param filePath The path towards the file.
 * @param fileName The name of the file that will be saved on the server.
 */
private void uploadFile(String filePath, String fileName) {

	InputStream inputStream;
	try {
		inputStream = new FileInputStream(new File(filePath));
		byte[] data;
		try {
			data = IOUtils.toByteArray(inputStream);

			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost("http://api.example.com/ping.php");

			InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
			MultipartEntity multipartEntity = new MultipartEntity();
			multipartEntity.addPart("file", inputStreamBody);
			httpPost.setEntity(multipartEntity);

			HttpResponse httpResponse = httpClient.execute(httpPost);

			// Handle response back from script.
			if(httpResponse != null) {

			} else { // Error, no response.

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	} catch (FileNotFoundException e1) {
		e1.printStackTrace();
	}
}

Edit the highlighted line to specify the location of the PHP script.
The server-side PHP script accepts the uploaded data and saves it to a file. It can look as follows:

<?php

    $objFile = & $_FILES["file"];
    $strPath = basename( $objFile["name"] );

    if( move_uploaded_file( $objFile["tmp_name"], $strPath ) ) {
        print "The file " .  $strPath . " has been uploaded.";
    } else {
        print "There was an error uploading the file, please try again!";
    }

Note that the identifier file must match in both the client-side Android Java code and the server-side PHP script.

Prerequisite: Apache Commons Library

IOUtils is provided by the Apache Commons library. You can download the jar here. Add the jar file to your Android application’s /lib folder and you’ll be good to go.

Leave a Reply

Your email address will not be published. Required fields are marked *