Uploading image from Android to GCS

后端 未结 5 1393
生来不讨喜
生来不讨喜 2020-12-01 04:02

I am trying to upload an image from Android directly to Google cloud storage. But the API does not seem to work. They have some Java samples which are tied to the App engine

5条回答
  •  猫巷女王i
    2020-12-01 04:37

    Fixed for Android:

    Android Studio config:

    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:

    
    
    

    Main implementation:

        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 Class:

    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 scopes = new ArrayList();
            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;
    }
    

提交回复
热议问题