我正在开发一款基于Android的应用程序,可与Google Cloud进行交互。我需要将图片上传到云端。我已经为PHP + Android开发了代码,但我不确定如何在Google Cloud(JAVA)中处理它。
Android代码:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
InputStream is;
BitmapFactory.decodeFile(data.getData().toString());
Bitmap bitmapOrg = BitmapFactory.decodeFile(selectedImagePath); //BitmapFactory.decodeResource(getResources(),R.drawable.gallery);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1 = Base64.encodeToString(ba, 1);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Custom user agent");
HttpPost httppost = new
HttpPost("http://umair-p.appspot.com/imageupload");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Toast.makeText(Main.this, is.toString(), Toast.LENGTH_LONG).show();
//Toast.makeText(Main.this, "Picture Shared", Toast.LENGTH_LONG).show();
}
catch(Exception e){
Toast.makeText(Main.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
//Toast.makeText(Main.this, data.getData().toString(), Toast.LENGTH_SHORT).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>';
?>
上述解决方案工作正常,但我需要将图片上传到Google Cloud。有什么帮助吗?
答案 0 :(得分:3)
您需要从AppEngine应用程序生成上传URL。
首先,执行HTTP GET到http://umair-p.appspot.com/imageupload
然后,在服务器上,调用blobstoreService.createUploadUrl(“/ imageupload”)。返回在HTTP响应中生成的URL。
最后,Android应用程序从响应中读取URL并在HTTP POST请求中使用它来上传图像。