php端接收代碼:
public function get_file(){ $local_path = "./Public/daixu_picture/figure/";//服務器文件的存放路徑 $img_name = basename( $_FILES['uploadedfile']['name']);//服務器中的圖片名(uploadedfile是鍵值名,可自行設定) $target_path = $local_path.$img_name; $result = move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path); if($result) { echo "上傳成功"; } else{ echo "上傳失敗"; } }
android端代碼:
/* * 作用:上傳圖片,並攜帶參數 * 傳入參數:http_url(服務器目標地址),filepath(本機圖片的地址) */ public void uploadImage(final String http_url, final String filepath){ new Thread(new Runnable() { @Override public void run() { try { File file = new File(filepath); if (!file.exists()) { Log.i("錯誤", "文件不存在"); } HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(http_url); FileBody fileBody = new FileBody(file, "image/jpeg"); MultipartEntity entity = new MultipartEntity(); entity.addPart("uploadedfile", fileBody);//uploadedfile是圖片上傳的鍵值名 entity.addPart("key_app", new StringBody("1",Charset.forName("UTF-8")));//設置要傳入的參數,key_app是鍵值名,此外傳參時候需要指定編碼格式 post.setEntity(entity); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toString(httpEntity, "utf-8"); Log.e("返回的結果",result); } }catch (Exception e) { e.printStackTrace(); } } }).start(); }