如何将图像从Android上传到GCS?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (85)

我现在对此感到震惊。有没有人尝试使用Java客户端或Json API从Android上载图像/视频并成功?请有人指点我正确的方向。Google的这款Storage api的体验非常令人失望。如果有人这样做,请分享下经验可以吗?

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;
}

我在这里遇到两个问题:

  1. 上传到服务器的文件已损坏。这与我上传的图片不一样。它已经结束。
  2. 授权密钥经常过期。在我的情况下,我使用gsutil生成的认证码。
提问于
用户回答回答于
用户回答回答于

固定为Android:

Android Studio配置:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile files('libs/android-support-v4.jar')
    compile files('google-play-services.jar')
    compile 'com.wu-man:android-oauth-client:0.0.3'
    compile 'com.google.apis:google-api-services-storage:v1-rev17-1.19.0'
    compile(group: 'com.google.api-client', name: 'google-api-client', version:'1.19.0'){
        exclude(group: 'com.google.guava', module: 'guava-jdk5')
    }
}

AndroidManifiest:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

主要实施:

    new AsyncTask(){

        @Override
        protected Object doInBackground(Object[] params) {
            try {

                CloudStorage.uploadFile("bucket-xxx", "photo.jpg");

            } catch (Exception e) {
                if(DEBUG)Log.d(TAG, "Exception: "+e.getMessage());
                e.printStackTrace();
            }
            return null;
        }
    }.execute();

CloudStorage类:

import com.google.api.services.storage.Storage;
import com.google.api.services.storage.StorageScopes;
import com.google.api.services.storage.model.Bucket;
import com.google.api.services.storage.model.StorageObject;

public static void uploadFile(String bucketName, String filePath)throws Exception {

    Storage storage = getStorage();
    StorageObject object = new StorageObject();
    object.setBucket(bucketName);
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,filePath);

    InputStream stream = new FileInputStream(file);

    try {
        String contentType = URLConnection.guessContentTypeFromStream(stream);
        InputStreamContent content = new InputStreamContent(contentType,stream);

        Storage.Objects.Insert insert = storage.objects().insert(bucketName, null, content);
        insert.setName(file.getName());
        insert.execute();

    } finally {
        stream.close();
    }
}

private static Storage getStorage() throws Exception {

    if (storage == null) {
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();
        List<String> scopes = new ArrayList<String>();
        scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);

        Credential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(ACCOUNT_ID_PROPERTY) //Email                           
                .setServiceAccountPrivateKeyFromP12File(getTempPkc12File())
                .setServiceAccountScopes(scopes).build();

        storage = new Storage.Builder(httpTransport, jsonFactory,
            credential).setApplicationName(APPLICATION_NAME_PROPERTY)
            .build();
    }

    return storage;
}

private static File getTempPkc12File() throws IOException {
    // xxx.p12 export from google API console
    InputStream pkc12Stream = AppData.getInstance().getAssets().open("xxx.p12");
    File tempPkc12File = File.createTempFile("temp_pkc12_file", "p12");
    OutputStream tempFileStream = new FileOutputStream(tempPkc12File);

    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = pkc12Stream.read(bytes)) != -1) {
        tempFileStream.write(bytes, 0, read);
    }
    return tempPkc12File;
}

扫码关注云+社区

领取腾讯云代金券