安卓上傳檔案至PHP伺服器

來源:互聯網
上載者:User

標籤:

前兩個月有幸參加一次免費培訓,開發了一款小軟體。發現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伺服器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.