2011-09-30 16 views
0

上傳圖片到服務器我用從網上的一些代碼上傳圖像無法在Android的

public class ActUpload extends Activity { 
InputStream is; 
public void onCreate(Bundle icicle) { 
super.onCreate(icicle); 
setContentView(R.layout.main); 
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), 
R.drawable.blue); 
ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao); 
byte [] ba = bao.toByteArray(); 
String ba1=Base64.encodeBytes(ba); 
ArrayList<NameValuePair> nameValuePairs = new 
ArrayList<NameValuePair>(); 
nameValuePairs.add(new BasicNameValuePair("image",ba1)); 
try{ 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new 
HttpPost("http://127.0.0.1:80/php/base.php"); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
HttpResponse response = httpclient.execute(httppost); 
HttpEntity entity = response.getEntity(); 
is = entity.getContent(); 
}catch(Exception e){ 
Log.e("log_tag", "Error in http connection "+e.toString()); 
} 
} 
} 

,甚至採取了一些PHP代碼複製到的我在本地服務器使用WAMP運行一些PHP代碼服務器。本地服務器沒有響應。 這是我的PHP代碼。

<?php 
$base=$_REQUEST['image']; 
echo $base; 
// base64 encoded utf-8 string 
$binary=base64_decode($base); 
// binary, utf-8 bytes 
header('Content-Type: bitmap; charset=utf-8'); 
// print($binary); 
//$theFile = base64_decode($image_data); 
$file = fopen('test.jpg', 'wb'); 
fwrite($file, $binary); 
fclose($file); 
echo '<img src=test.jpg>'; 
?> 

任何人都可以幫助我。提前致謝。

+0

從哪裏得到這個PHP代碼? –

+0

我從我得到java代碼的同一鏈接中獲得代碼。我剛剛複製了它。 – user973049

+0

TCP堆棧上的127.0.0.1是環回地址。你的Android設備正試圖發佈給自己,而不是你的wamp服務器。 –

回答

0

一個很好的教程上傳圖片服務器 -

http://coderzheaven.com/2011/04/android-upload-an-image-to-a-server/

編輯:

你只需要根據自己的本地服務器可以改變:

HttpPost httppost = new HttpPost("http://<local ip address>/android/upload_image.php"); 

// For example,in my code,i used: 
// HttpPost httppost = new HttpPost("http://192.168.100.47/android/upload_image.php"); 
+0

我已經按照教程進行了修改,並按照我的需要進行了更改,並根據本地系統服務器提供了http://127.0.0.1:80/Upload_image_ANDROID/upload_image.php,但沒有得到結果。你能告訴我任何建議嗎? – user973049

+0

@ user973049:當我使用這段代碼時,它在我的本地服務器上工作正常。你是否收到任何錯誤?你能告訴我更多的代碼嗎? – Hiral

+0

@ user973049:請在回答中檢查我的編輯。 – Hiral

0

難道你設法解決問題?我改變了$ base = $ _ REQUEST ['image']; => $ base = $ _ POST ['image'];並註釋掉以下行標題('Content-Type:bitmap; charset = utf-8');順便說一句,沒有嘗試將代碼轉換爲使用HttpURLConnection API?