2012-04-26 57 views
0

我一直在寻找一个程序来上传一张照片,我用我的相机拍摄并存储在位图到我自己的网站。我试过下面的代码,但没有成功。将照片上传到自己的网站

 public void onClick(View v) { 
      ByteArrayOutputStream bytearrayStream = new ByteArrayOutputStream(); 
      bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 90, bytearrayStream); 
      byte [] byteArray = bytearrayStream.toByteArray(); 
      String byteArrayToString = Base64.encodeBytes(byteArray); 
      ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
      nameValuePairs.add(new BasicNameValuePair("image", byteArrayToString)); 

      try{ 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost("http://www.mywebsite.com/upload_image.php"); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
       stream = entity.getContent(); 

       Toast text = Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG); 
       text.show(); 
      } 
      catch(Exception e){ 
       Log.e("log_tag", "Error in http connection " + e.toString()); 
       Toast text = Toast.makeText(getApplicationContext(), "FOUT", Toast.LENGTH_LONG); 
       text.show(); 

      } 
     } 

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 />'; 
?> 

如果我尝试在本地主机上的PHP文件,它使一个test.jpg放在。所以我认为如果$_REQUEST['image']不为空,则会创建正确的文件。

如果在try-area中没有错误,我的android程序会显示一个toasttext'OK'。如果有错误,则显示'FOUT'。在测试我的Xperia时,它总是显示OK ...

有什么建议吗?

回答

0

试试这个

public void executeMultipartPost() throws Exception { 
try { 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
bm.compress(CompressFormat.JPEG, 75, bos); 
byte[] data = bos.toByteArray(); 
HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost postRequest = new HttpPost("http://www.mywebsite.com/upload_image.phpamp"); 
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg"); 

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
reqEntity.addPart("uploaded", bab); 
reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf")); 
postRequest.setEntity(reqEntity); 
HttpResponse response = httpClient.execute(postRequest); 
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
String sResponse; 
StringBuilder s = new StringBuilder(); 

while ((sResponse = reader.readLine()) != null) { 
s = s.append(sResponse); 
    } 
System.out.println("Response: " + s); 
} catch (Exception e) { 
    // handle exception here 
    Log.e(e.getClass().getName(), e.getMessage()); 
    } 
}