2013-08-26 214 views
-3

在我的應用程序文件,我已經到CSV文件發送到服務器 我嘗試下面的代碼安卓:發送文件到服務器:PHP接收服務器

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

和我的PHP代碼..

<?php 


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

其他 {

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"]; 
    } 
} 

?> 

我得到了錯誤

08-26 17:29:18.318:I /編輯的用戶簡檔(700):
08-26 17:29:18.318:I /編輯的用戶簡檔(700):通知:未定義指數:檢測在C:\ XAMPP \ htdocs中\ sendreport.php上線

回答

4

我希望它會工作

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

也看到,http://www.codeofaninja.com/2013/04 /android-http-client.html – 2013-08-27 08:12:59

+0

謝謝。奇蹟般有效 !!! –