Android: Sending file to server : PHP receive that file in server

▼魔方 西西 提交于 2019-11-30 16:45:58

I hope it will work

 // the file to be posted
String textFile = Environment.getExternalStorageDirectory() + "/sample.txt";
 Log.v(TAG, "textFile: " + textFile);

 // the URL where the file will be posted
 String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
Log.v(TAG, "postURL: " + postReceiverUrl);

 // new HttpClient
 HttpClient httpClient = new DefaultHttpClient();

// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);

File file = new File(textFile);
FileBody fileBody = new FileBody(file);

MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);

// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

if (resEntity != null) {

String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " +  responseStr);

// you can add an if statement here and do other actions based on the response
}

and php code.
<?php
// if text data was posted
if($_POST){
print_r($_POST);
}

 // if a file was posted
 else if($_FILES){
 $file = $_FILES['file'];
 $fileContents = file_get_contents($file["tmp_name"]);
 print_r($fileContents);
 }
 ?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!