I am a new Android learner. I was trying to upload a textfile from SD card to a remote server. I have written the PHP script in such a way that If the file is set it will do file operations and response "Success!" else it will response "File is not set!". Here is the PHP Script -
<?php
if(isset($_FILES["file"])){
/* Do file operations */
echo "Success!";
}
else{
die("file is not set!");
}
?>
It always responses "file is not set!". May be its not recognizing the "file" index in $_FILES[]. Can't understand why!
Here is the android part for uploading file:
/* Location of the file */
String filePath = Environment.getExternalStorageDirectory() + "/sample.txt";
/* URL of the PHP script for file processing */
String URL = "http://myserver/upload.php";
/* New HTTP Client */
HttpClient client = new DefaultHttpClient();
/* Post */
HttpPost post = new HttpPost(URL);
/* Create file from file path */
File file = new File(filePath);
FileBody fileBody = new FileBody(file);
/* Make MultipartEntity from File Body and send */
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
/* Execute Http post request and get response */
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
/* Make response entity into string to get string response */
String responseString = EntityUtils.toString(resEntity);
Toast.makeText(getApplicationContext(), responseString, Toast.LENGTH_SHORT).show();
}
And here is full PHP part:
<?php
if(isset($_FILES["file"])){
$file_path = "upload/" . basename($_FILES["file"]["name"]);
if(move_uploaded_file($_FILES["file"]["tmp_name"], $file_path)){
echo "Success!";
}
else{
echo "Failed!";
}
}
else{
die("file is not set!");
}
?>
0 comments:
Post a Comment