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

一笑奈何 提交于 2019-11-30 00:03:22

问题


In my application i have to send the csv file to server i tried the following code

            HttpPost httppost = new HttpPost(url);

        InputStreamEntity reqEntity = new InputStreamEntity(
                new FileInputStream(file), -1);
        reqEntity.setContentType("binary/octet-stream");
        reqEntity.setChunked(true); // Send in multiple parts if needed
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);

and my php code is..

<?php


if ($_FILES["detection"]["error"] > 0)
{
echo "Return Code: " . $_FILES["detection"]["error"] . "<br>";
 }

else {

 if (file_exists($_FILES["detection"]["name"]))
  {
   echo $_FILES["detection"]["name"] . " already exists. ";
  }
 else
   {
  move_uploaded_file($_FILES["detection"]["tmp_name"],$_FILES["detection"]["name"]);
  echo "Stored in: ". $_FILES["detection"]["name"];
   }
 }

?>

i got the error that

08-26 17:29:18.318: I/edit user profile(700):
08-26 17:29:18.318: I/edit user profile(700): Notice: Undefined index: detection in C:\xampp\htdocs\sendreport.php on line 4


回答1:


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);
 }
 ?>


来源:https://stackoverflow.com/questions/18442021/android-sending-file-to-server-php-receive-that-file-in-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!