在我的Android应用程序中,我要将文件上传到服务器并在服务器端读取文件。正在上载文件但有时会发生在文件夹中(在文件所在的服务器中)如果存在先前上载的文件,则使用先前的文件数据生成当前上载的文件。例如如果我将名为 A 的文件上传到服务器,数据说'1,2和3'那么服务器端的文件夹下面会有文件A.txt
数据,如果现在我将名为 B 的文件上传到服务器,数据说'A,B和C',那么文件夹下的文件B.txt
就会出现但是以前的A.txt
文件数据。因此,在B.txt
中,数据'1,2和3'。以下是我的代码。可能是什么问题?
public void uploadUserFriendId(String user_id, String filePath, String fileName)
{
String server_url = "http://addressofserver/folder/myfile.php";
InputStream inputStream;
try
{
inputStream = new FileInputStream(new File(filePath));
byte[] data;
try
{
data = IOUtils.toByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
System.getProperty("http.agent"));
HttpPost httpPost = new HttpPost(server_url);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("file", inputStreamBody);
multipartEntity.addPart("user_id", new StringBody(user_id));
httpPost.setEntity(multipartEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
// Handle response back from script.
if(httpResponse != null) {
//Toast.makeText(getBaseContext(), "Upload Completed. ", 2000).show();
} else { // Error, no response.
//Toast.makeText(getBaseContext(), "Server Error. ", 2000).show();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
<?php
error_reporting(~0);
ini_set('display_errors', 1);
mysql_connect("localhost", "root", "Admin@123") or die(mysql_error()) ;
mysql_select_db("retail_menu") or die(mysql_error()) ;
$today =date("YmdHis");
$pic=$today.".txt";
if (isset($_POST["user_id"]) && !empty($_POST["user_id"]))
{
$user_id=$_POST['user_id'];
}
else
{
$user_id="null";
}
$objFile = & $_FILES["file"];
// here file is created under folder named upload at server side
if( move_uploaded_file( $objFile["tmp_name"], "upload/".$user_id.".txt" ) )
{
$file = fopen("upload/".$user_id.".txt" ,"r");
while(! feof($file))
{
$friend_id = fgets($file, 8192);
if($friend_id!= null)
{
$query = "INSERT IGNORE INTO table_name (user_id, friend_id) values('$user_id', '$friend_id')";
var_dump($query);
mysql_query($query);
}
}
fclose($file);
}
else
{
print "There was an error uploading the file, please try again!";
}
?>