2012-06-23 27 views
2

我在android中上传。为此,我按照tutorial。我当前的代码给了我这个错误在我的logcat使用base64上传图像并在android中发送参数

06-23 10:10:22.990: D/dalvikvm(25853): GC_EXTERNAL_ALLOC freed 48K, 50% free 2723K/5379K, external 0K/0K, paused 33ms 
06-23 10:10:23.030: E/log_tag(25853): Error in http connection java.net.UnknownHostException: www.example.info 
06-23 10:10:23.115: D/CLIPBOARD(25853): Hide Clipboard dialog at Starting input: finished by someone else... ! 

这里是我的代码看起来像

public class UploadFileActivity extends Activity { 
/** Called when the activity is first created. */ 
Button bUpload; 
EditText etParam; 

InputStream is; 

@Override 

public void onCreate(Bundle icicle) { 

    super.onCreate(icicle); 
    setContentView(R.layout.main); 

    Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); 
    ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao); 

    byte [] ba = bao.toByteArray(); 
    String ba1=Base64.encodeToString(ba, 0); 

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("image",ba1)); 

    try { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://www.example.info/androidfileupload/index.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 
$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

有时也会发生,如果权限已被使用,只需重新启动'Wifi'或'MobileData' –

回答

2

UnknownHostException是什么与您的网址域有关或者没有互联网/网络连接,

因此,请确保您已在您的AndroidManifest文件中添加了Internet权限。

<uses-permission android:name="android.permission.INTERNET" /> 

希望这有助于

+0

由于它的工作原理。你能告诉我如何保留图像的名称作为原始名称?我的意思是,我想在上传时使用该图像的相同名称。 – 2619

2

我遵循同样的教程。只要图像足够小就可以工作。

否则你可以在内存问题的out:

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

要回答你的问题 -

你能告诉我怎样才能保持图像的名称作为原始 名?我的意思是,我想在上传 时使用该图像的相同名称。

您可以向包含原始名称的URL请求添加一个变量。否则,您将无法将其嵌入64Byte编码的字符串中。

事情是这样的:

"http://www.example.info/androidfileupload/index.php?name=filename" 

PHP侧面看上去就像是

$FileName = $_GET['name']; 
相关问题