![](/img/trans.png)
[英]Sending base64 encoded image to server using HttpUrlConnection Android
[英]upload image and sending parameter in android using base64
我正在android中上傳。 為此,我正在遵循本教程 。 我當前的代碼在我的logcat中給了我這個錯誤
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>';
?>
UnknownHostException
與您的網址域相關,或者沒有Internet /網絡連接,
因此,請確保已在AndroidManifest文件中添加了Internet權限。
<uses-permission android:name="android.permission.INTERNET" />
希望這可以幫助
我遵循了相同的教程。 只要圖像足夠小就可以工作。
否則,您可以在以下位置遇到內存不足的問題:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
要回答您的問題-
您能告訴我如何將圖像名稱保留為原始名稱嗎? 我的意思是,我想在上傳時使用相同的圖片名稱。
您可以向擁有原始名稱的URL請求添加一個變量。 否則,您將無法將其嵌入到64Byte編碼的字符串中。
像這樣:
"http://www.example.info/androidfileupload/index.php?name=filename"
PHP方面看起來像
$FileName = $_GET['name'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.