標籤:
前兩個月有幸參加一次免費培訓,開發了一款小軟體。發現AsyncHttpClient還真是好用。
直奔主題,安卓上傳檔案至PHP伺服器:
1.PHP端伺服器:
<?php//連結資料庫include ("config/db.php");//擷取使用者id$userid = $_POST[‘userid‘];//處理上傳檔案$base_path = "upload/"; $fileName=$_FILES[‘file‘][‘name‘]; $name=explode(‘.‘,$fileName); $userpicads = $base_path . ‘user_‘.$userid. ‘.‘ .$name[1]; /*返回狀態代碼:300: 處理成功301:伺服器異常*/$status=301;if (move_uploaded_file ( $_FILES [‘file‘] [‘tmp_name‘], $userpicads )) { $status=300; } else { $status=301; }//如果儲存檔案成功,更新資料庫if($status==300){$sql = "update mh_user set userpicads=‘{$userpicads}‘ where id={$userid}";$pdo->exec($sql);}//輸出返回結果$ret = array(‘status‘=> $status);echo json_encode($ret);?>
2.安卓端添加網路許可權
<uses-permission android:name="android.permission.INTERNET" />
3.安卓端匯入以下jar包(這些很容易就能下載到):
android-async-http-1.4.7.jar (必須)
gson-2.1.jar (可選,解析json格式用)
httpcore-4.4.4.jar(可選,用Android Stutio可能還需要匯入這個)
4.安卓主要代碼:
int userid = 1;String username = "HelloWorld";String filepath = "/mnt/sdcard/Download/mm.jpg";String uploadUrl = "http://192.168.1.103/test/upload.php";btn_upload.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {AsyncHttpClient client = new AsyncHttpClient();RequestParams params = new RequestParams();//添加參數params.put("userid", userid);params.put("username", username);try {//添加檔案params.put("file", new File(filepath));} catch (FileNotFoundException e) {e.printStackTrace();}client.post(uploadUrl, params, new AsyncHttpResponseHandler() {@Overridepublic void onSuccess(int i, org.apache.http.Header[] headers, byte[] bytes) {try {//擷取返回內容String resp = new String(bytes, "utf-8");//在這裡處理返回的內容,例如解析json什麼的...} catch (UnsupportedEncodingException e) {e.printStackTrace();}}@Overridepublic void onFailure(int i, org.apache.http.Header[] headers, byte[] bytes, Throwable throwable) {//在這裡處理串連失敗的處理...}});}});
本文主要參考:
http://blog.csdn.net/fancylovejava/article/details/13506745
PHP如何重新命名上傳的檔案:
http://zhidao.baidu.com/link?url=lipsDeUjztDw-kwpcWcs7b16_GEer7T2r7wBM3MMzRpBCZuct-wikqv6j5vsZxK39KotlB8qH8bVXOqRCXHosq
Android Studio 可能找不到 org.apache.http.Header,參考:
http://zhidao.baidu.com/link?url=_RM6ndKff2FpUf6i-I97FiyKpnwPsHCg7EgYFXjTJgAhZlLN8DlT55VX02sD3epoEw72BWU2xbWqLN_yfHXBGw0nKxqbctMzSbo51UPePRi
安卓上傳檔案至PHP伺服器