【问题标题】:how I can upload any file or image to Google cloud Storage from Android如何从 Android 将任何文件或图像上传到 Google 云存储
【发布时间】:2016-06-21 22:16:13
【问题描述】:

我想将文件从 Android 设备上传到 Google Cloud Storage。为此,我使用 JSON API 在 Google 云中创建了项目并创建了与之相关的存储桶。然后创建服务帐户密钥,即 p12 文件。

但后来卡住了如何在 Android 编程中编写代码。

【问题讨论】:

    标签: android upload google-cloud-storage


    【解决方案1】:
    private static String uploadFile(RichMedia media) {
    DefaultHttpClient client = new DefaultHttpClient();
    Bitmap bitmap = BitmapUtils.getBitmap(media.getLocalUrl());
    HttpPost post = new HttpPost(GCS_ROOT + media.getLocalUrl() + "_" + System.currentTimeMillis());
    if(media.getType() == RichMedia.RichMediaType.PICTURE) {
        post.setHeader("Content-Type", "image/jpeg");
    } else {
        post.setHeader("Content-Type", "video/mp4");
    }
    post.setHeader("Authorization", "AIzaSyCzdmCMwiMzl6LD7R2obF0xSgnnx5rEfeI");
    //post.setHeader("Content-Length", String.valueOf(bitmap.getByteCount()));
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    
    try {
        post.setEntity(new StringEntity(new Gson().toJson(byteArray).toString()));
        HttpResponse response = client.execute(post);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String eachLine = null;
        StringBuilder builder = new StringBuilder();
        while ((eachLine = reader.readLine()) != null) {
            builder.append(eachLine);
        }
        L.d("response = " + builder.toString());
        JSONObject object = new JSONObject(builder.toString());
        String name = object.getString("name");
        return  name;
    } catch (IOException e) {
        L.print(e);
    } catch (JSONException e) {
        L.print(e);
    }
    return null;
    

    }

    你可以从这段代码中学习

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 2021-09-28
      • 1970-01-01
      • 2017-05-04
      • 2015-02-28
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 2018-12-22
      相关资源
      最近更新 更多