カメラで撮った写真をビットマップ形式で自分の Web サイトにアップロードするプログラムを探していました。次のコードを試しましたが、失敗しました。
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 />';
?>
localhost で php ファイルを試してみると、test.jpg が作成されます。$_REQUEST['image']
したがって、null でない場合は、正しいファイルが作成されると思います。
トライエリアにエラーがない場合、私のアンドロイドプログラムはトーストテキスト「OK」を表示します。エラーがある場合は「FOUT」と表示されます。私のXperiaでテストすると、常にOKと表示されます...
助言がありますか?