简体   繁体   English

在Android中以编程方式使用Google Drive API将图像上传到Google Drive

[英]Upload image to a google drive using google drive api programatically in android

I am able to uploading a text file to folder in google drive using google drive android api . 我可以使用google drive android api将文本文件上传到google drive中的文件夹。 Sample code 样例代码

But i would like to uplaod a image to google drive .Is it possible? 但是我想将一张图片升级到Google Drive。这可能吗?

code for create text file: 用于创建文本文件的代码:

final private ResultCallback<DriveContentsResult> driveContentsCallback = new
        ResultCallback<DriveContentsResult>() {
    @Override
    public void onResult(DriveContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            showMessage("Error while trying to create new file contents");
            return;
        }
        final DriveContents driveContents = result.getDriveContents();

        // Perform I/O off the UI thread.
        new Thread() {
            @Override
            public void run() {
                // write content to DriveContents
                OutputStream outputStream = driveContents.getOutputStream();
                Writer writer = new OutputStreamWriter(outputStream);
                try {
                    writer.write("Hello World!");
                    writer.close();
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage());
                }

                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                        .setTitle("New file")
                        .setMimeType("text/plain")
                        .setStarred(true).build();

                // create a file on root folder
                Drive.DriveApi.getRootFolder(getGoogleApiClient())
                        .createFile(getGoogleApiClient(), changeSet, driveContents)
                        .setResultCallback(fileCallback);
            }
        }.start();
    }
};

Now i need MimeType("image/jpeg") and i have to change OutputStreamWriter? 现在我需要MimeType(“ image / jpeg”),我必须更改OutputStreamWriter吗?

Any help appreciated..:) 任何帮助表示赞赏.. :)

WARNING : The Drive Android API is deprecated as of December 6, 2018 and will be turned down on December 6, 2019. Hence you shouldn't upload images to Google Drive for storage purpose, you should use Firebase / other solutions 警告:Drive Android API自2018年12月6日起弃用,并将于2019年12月6日被拒绝。因此,您不应将图像上传到Google Drive进行存储,应使用Firebase /其他解决方案

Your code is for uploading Text File. 您的代码用于上传文本文件。 To upload a Image file, use below code: 要上传图片文件,请使用以下代码:

private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;


private void saveFileToDrive() {

    final Bitmap image = mBitmapToSave;
    Drive.DriveApi.newDriveContents(mGoogleApiClient)
            .setResultCallback(new ResultCallback<DriveContentsResult>() {

        @Override
        public void onResult(DriveContentsResult result) {

            if (!result.getStatus().isSuccess()) {
                Log.i("ERROR", "Failed to create new contents.");
                return;
            }


            OutputStream outputStream = result.getDriveContents().getOutputStream();
            // Write the bitmap data from it.
            ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
            try {
                outputStream.write(bitmapStream.toByteArray());
            } catch (IOException e1) {
                Log.i("ERROR", "Unable to write file contents.");
            }
            // Create the initial metadata - MIME type and title.
            // Note that the user will be able to change the title later.
            MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                    .setMimeType("image/jpeg").setTitle("Android Photo.png").build();
            // Create an intent for the file chooser, and start it.
            IntentSender intentSender = Drive.DriveApi
                    .newCreateFileActivityBuilder()
                    .setInitialMetadata(metadataChangeSet)
                    .setInitialDriveContents(result.getDriveContents())
                    .build(mGoogleApiClient);
            try {
                startIntentSenderForResult(
                        intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
            } catch (SendIntentException e) {
                Log.i("ERROR", "Failed to launch file chooser.");
            }
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    if (mGoogleApiClient == null) {
        // Create the API client and bind it to an instance variable.
        // We use this instance as the callback for connection and connection
        // failures.
        // Since no account name is passed, the user is prompted to choose.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    // Connect the client. Once connected, the camera is launched.
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
    super.onPause();
}

Also Implements ConnectionCallbacksand and OnConnectionFailedListener Listeners. 还实现ConnectionCallbacksandOnConnectionFailedListener侦听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM