在我的应用程序中,我必须将csv文件发送到服务器 我尝试了以下代码
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:我/编辑用户档案(700):
08-26 17:29:18.318:我/编辑用户档案(700):通知:未定义的索引: C:\ xampp \ htdocs \ sendreport.php 中的检测 4
答案 0 :(得分: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);
}
?>