我正在开发一个基于 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。有什么帮助吗?
最佳答案
您需要从 AppEngine 应用程序生成上传 URL。
首先,对 http://umair-p.appspot.com/imageupload 执行 HTTP GET
然后,在服务器上调用 blobstoreService.createUploadUrl("/imageupload")。返回在 HTTP 响应中生成的 URL。
最后,Android 应用从响应中读取 URL,并在 HTTP POST 请求中使用它来上传图像。
关于java - 如何将图像从 Android 上传到 Google Cloud (Java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5896981/