Friday, April 4, 2014

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.

Prerequisite:

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.

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!";

}
>


No comments:

Post a Comment