【问题标题】:Upload image to a google drive using google drive api programatically in android在android中以编程方式使用google drive api将图像上传到google drive
【发布时间】:2017-03-20 18:46:37
【问题描述】:

我可以使用 google drive android api 将文本文件上传到 google drive 中的文件夹。Sample code

但我想将图像上传到谷歌驱动器。可以吗?

创建文本文件的代码:

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

现在我需要 MimeType("image/jpeg") 并且我必须更改 OutputStreamWriter?

任何帮助表示赞赏..:)

【问题讨论】:

    标签: android file-upload image-uploading google-drive-android-api


    【解决方案1】:

    警告:Drive Android API 自 2018 年 12 月 6 日起弃用,并将于 2019 年 12 月 6 日停用。因此,您不应将图像上传到 Google Drive 以进行存储,您应该使用 Firebase /其他解决方案

    您的代码用于上传文本文件。要上传图像文件,请使用以下代码:

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

    还实现了ConnectionCallbacksandOnConnectionFailedListener听众。

    【讨论】:

    • 您将在哪里获得 driveId?我有几乎相似的代码,但由于某种原因 driveId 总是为空。有什么想法吗?
    • 尝试result.getDriveContents().getDriveId() 获取driveId
    • 当您上传文件或文件夹时,它会返回一个驱动器 ID。仅使用该 ID,我们将获得该关联文件或文件夹 @creepy_driver
    • @AsifPatel 非常感谢您的解决方案。我怎样才能下载图像或如何向用户显示此图像。我将此图像保存在 appfolder 中。
    猜你喜欢
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多