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.

20 thoughts on “Android Uploading a File to a PHP Server

  1. Aiman Reply

    Hey, nice post. But, what kind of path does the fileName accept? Can you give us an example? A Log.d perhaps.

  2. Choucky Reply

    Hello !
    I have a failure when I launch uploadFile(), Error: Faillure delivering result ResultInfo…..
    I consult a directory regularly and consult if there is one new file. If there is a new file I the upload with this function. But I don’t understand why I have an Fatal Exception.

  3. Anonymous Reply

    I am able to upload file on server but when I download it again same file from server , I am unable to open it.
    If i uploaded text file then it seems a blank file of same name uploaded on server it contains nothing.

  4. Prathy Reply

    hey can you please provide me the jar for InputStreamBody. Thanks

  5. vj Reply

    How to do if i want send some editText datas with upload image ? can i send using string using mulitpartentity? if yes how?

  6. waseem Reply

    Hey Dear, i am new in android. i have made an application that communicate between user by text messages using sockets and xampp server. now i want to attach some FILES like image and send it to other user… please help me…. thanks for any help…

  7. Ahsan Reply

    Hi, how to cancel upload when uploading is in progress using this code?

  8. ali Reply

    Hi. Thank You for your content.
    i have a Question.
    i want to calculate amount size of uploaded file in any time,
    how i can get this parameters ?
    and finally i want to show percent of uploading in ProgressBar.
    please Help me.

Leave a Reply

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