此為介紹Android 上傳檔案如何用base64 String來上傳的方法
先看一下android 處理圖片轉換為base64上傳的流程圖
在開始之前記得先在你android專案的AndroidManifest.xml中加入充許使用網路的權限
<uses-permission android:name="android.permission.INTERNET"/>
在此我們需要額外下載base64.java檔
連結到 http://iharder.sourceforge.net/current/java/base64/
下載base64-v2.3.7.zip解壓後會得到Base64.java檔將此檔案加入你的android專案中
加入後此檔案會出現錯誤,請在第一行加上你android專案的package
如下圖所示
可在此下載java程式碼:http://blog.sptechnolab.com/wp-content/uploads/2011/03/bitmap.pdf
程式碼如下:
public class upload extends Activity {
InputStream is;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.a1);
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://10.0.2.2:80/android/base.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
/* http response 200 = ok */
Log.v(TAG, "http response status: "+httpResponse.getStatusLine().getStatusCode());
if (httpResponse.getStatusLine().getStatusCode() == 200) {
/* get data from server url */
String strResult = EntityUtils.toString(httpResponse.getEntity());
Log.d(TAG, "get Result:"+strResult);
} else {
//tools.showInfo("upload file error: "+httpResponse.getStatusLine().getStatusCode());
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
}
server 程式碼以php為範例:http://blog.sptechnolab.com/wp-content/uploads/2011/03/uploadphp.pdf
程式碼如下:
<?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>';
?>
好歹也貼個原始著作連結吧?