我是一名新的Android学员。我试图将文本文件从SD卡上传到远程服务器。我已经编写了PHP脚本,如果文件被设置,它将执行文件操作并响应“成功!”否则它将响应“文件未设置!”。这是PHP脚本 -
<?php
if(isset($_FILES["file"])){
/* Do file operations */
echo "Success!";
}
else{
die("file is not set!");
}
?>
它始终响应“文件未设置!”。可能是它无法识别$ _FILES []中的“文件”索引。无法理解为什么!
以下是上传文件的android部分:
/* 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();
}
这里是完整的PHP部分:
<?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!");
}
?>