【问题标题】:How to get url of uploaded file to google drive in android using Drive API?如何使用 Drive API 将上传文件的 url 获取到 android 中的谷歌驱动器?
【发布时间】:2017-08-02 19:35:09
【问题描述】:

我需要获取我上传到谷歌驱动器的视频的链接,以便我可以在网络浏览器中打开视频,我可以将视频文件上传到谷歌驱动器,还可以使用以下方法获取文件 ID代码:

private void UploadFile(final DriveId driveId)
{
    Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
        @Override
        public void onResult(@NonNull DriveApi.DriveContentsResult driveContentsResult)
        {
            if (!driveContentsResult.getStatus().isSuccess())
            {
                Log.e(TAG, "Error while trying to create new file contents");
                return;
            }
            OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
            Toast.makeText(context, "Uploading to drive....", Toast.LENGTH_LONG).show();
            final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/VideoFiles/testVideo.mkv");
            try
            {
                FileInputStream fileInputStream = new FileInputStream(theFile);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1)
                {
                    outputStream.write(buffer, 0, bytesRead);
                }
            } catch (IOException e1)
            {
                Log.i(TAG, "Unable to write file contents.");
            }
            MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mkv").setStarred(false).build();
            DriveFolder folder = driveId.asDriveFolder();
            folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>() {
                        @Override
                        public void onResult(@NonNull DriveFolder.DriveFileResult driveFileResult)
                        {
                            if (!driveFileResult.getStatus().isSuccess())
                            {
                                Log.e(TAG, "Error while trying to create the file");
                                return;
                            }
                            Log.v(TAG, "Created a file: " + driveFileResult.getDriveFile().getDriveId());
                        }
                    });
        }
    });
}

我尝试使用以下代码获取视频网址:

DriveFile file = Drive.DriveApi.getFile(googleApiClient,driveId);
                            DriveResource.MetadataResult mdRslt = file.getMetadata(googleApiClient).await();
                            if (mdRslt != null && mdRslt.getStatus().isSuccess()) {
                                String link = mdRslt.getMetadata().getWebContentLink();
                                Log.d("LINK", link);
                            }

但后来我得到“无法解析符号 'googleApiClient' 请问有什么建议吗?

【问题讨论】:

  • 这是因为googleApiClient 没有定义。你应该使用mGoogleApiClient,就像你在代码中的其他地方一样。
  • 感谢重播,但我注意到我从 driveFileResult.getDriveFile().getDriveId() 获得的文件 ID 未完成:“DriveId:CAESABiwayCK16yy6VAoAA==" 这对我来说很奇怪吗?如果我正确,那么我可以通过添加一些以drive.google.com/......File ID 开头的字符串来构建 url .....
  • 这里有一个线索。您的代码显示“正在上传到驱动器....”,但您使用的是 GDAA,因此您没有上传到驱动器。您所做的只是将文件保存在本地。一段时间后,Play 服务会将您的文件同步到云端硬盘。

标签: google-drive-api google-drive-android-api


【解决方案1】:

好的,我找到了解决方案,首先我必须通过使用更改事件侦听器来获取完成的文件 ID,然后我们可以将“drive.google.com/open?id=”添加到文件 ID,所以编译url 将是 drive.google.com/open?id=FileID。 这是我的答案:

public class Uploader extends Activity implements ConnectionCallbacks,OnConnectionFailedListener{
private static final String TAG = "Google Drive Activity";
private static final int REQUEST_CODE_RESOLUTION = 1;
private static final  int REQUEST_CODE_OPENER = 2;
private GoogleApiClient mGoogleApiClient;
public DriveFile file;
private String FOLDER_NAME = "GD_VideoFile";
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onResume()
{
    super.onResume();
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    mGoogleApiClient.connect();
}

@Override
protected void onStop()
{
    super.onStop();
    if (mGoogleApiClient != null) {

        mGoogleApiClient.disconnect();
    }
    super.onPause();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult result)
{
    Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
    if (!result.hasResolution()) {

        GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
        return;
    }

    try {

        result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);

    } catch (SendIntentException e) {

        Log.e(TAG, "Exception while starting resolution activity", e);
    }
}

@Override
public void onConnected(Bundle connectionHint)
{
    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();

    if (mGoogleApiClient != null)
    {
        check_folder_exists();
    } else
    {
        Log.e(TAG, "Could not connect to google drive manager");
    }
}

@Override
public void onConnectionSuspended(int cause)
{
    Log.i(TAG, "GoogleApiClient connection suspended");
}

@Override
protected void onActivityResult(final int requestCode,
                                final int resultCode, final Intent data)
{
    switch (requestCode)
    {
        case REQUEST_CODE_OPENER:
            if (resultCode == RESULT_OK)
            {
                DriveId mFileId = data.getParcelableExtra(
                        OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
                Log.e("file id", mFileId.getResourceId() + "");
                String url = "https://drive.google.com/open?id="+ mFileId.getResourceId();
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}

private void check_folder_exists()
{
    Query query = new Query.Builder().addFilter(Filters.and(Filters.eq(SearchableField.TITLE, FOLDER_NAME), Filters.eq(SearchableField.TRASHED, false))).build();
    Drive.DriveApi.query(mGoogleApiClient, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
        @Override
        public void onResult(@NonNull DriveApi.MetadataBufferResult result)
        {
            if (!result.getStatus().isSuccess())
            {
                Log.e(TAG, "Cannot create folder in the root.");
            } else
            {
                boolean isFound = false;
                for (Metadata m : result.getMetadataBuffer())
                {
                    if (m.getTitle().equals(FOLDER_NAME)) {
                        Log.e(TAG, "Folder exists");
                        isFound = true;
                        DriveId driveId = m.getDriveId();
                        UploadFile(driveId);
                        break;
                    }
                }
                if (!isFound)
                {
                    Log.i(TAG, "Folder not found; creating it.");
                    MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(FOLDER_NAME).build();
                    Drive.DriveApi.getRootFolder(mGoogleApiClient)
                            .createFolder(mGoogleApiClient, changeSet)
                            .setResultCallback(new ResultCallback<DriveFolder.DriveFolderResult>() {
                                @Override
                                public void onResult(@NonNull DriveFolder.DriveFolderResult result)
                                {
                                    if (!result.getStatus().isSuccess())
                                    {
                                        Log.e(TAG, "Error while trying to create the folder");
                                    } else {
                                        Log.i(TAG, "Created a folder");
                                        DriveId driveId = result.getDriveFolder().getDriveId();
                                        UploadFile(driveId);
                                    }
                                }
                            });
                }
            }
        }
    });
}


private void UploadFile(final DriveId driveId)
{

    Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>()
    {
        @Override
        public void onResult(@NonNull DriveApi.DriveContentsResult driveContentsResult)
        {
            if (!driveContentsResult.getStatus().isSuccess())
            {
                Log.e(TAG, "U AR A MORON! Error while trying to create new file contents");
                return;
            }

            OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
            Toast.makeText(Uploader.this, "Uploading to drive....", Toast.LENGTH_LONG).show();
            final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyMobile_Videos/a.mov");
            try
            {
                FileInputStream fileInputStream = new FileInputStream(theFile);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1)
                {
                    outputStream.write(buffer, 0, bytesRead);
                }
            } catch (IOException e1)
            {
                Log.i(TAG, "Unable to write file contents.");
            }

            MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mov").setStarred(false).build();
            DriveFolder folder = driveId.asDriveFolder();
            folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>()
            {
                        @Override
                        public void onResult(@NonNull DriveFolder.DriveFileResult driveFileResult)
                        {
                            if (!driveFileResult.getStatus().isSuccess())
                            {
                                Log.e(TAG, "Error while trying to create the file");
                                return;
                            }
                            Toast.makeText(Uploader.this, "Created a file: " + driveFileResult.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();

                            String Folder_Id = driveId.getResourceId();
                            System.out.println("The folder id: " +Folder_Id);

                            //This is to get the file id from the listener
                            DriveId File_Uncompleted_Id = driveFileResult.getDriveFile().getDriveId();
                            DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, File_Uncompleted_Id);
                            file.addChangeListener(mGoogleApiClient, changeListener);
                        }

                //A listener to handle file change events.
                final private ChangeListener changeListener = new ChangeListener()
                {
                    @Override
                    public void onChange(ChangeEvent event)
                    {
                        String File_Completed_Id =  event.getDriveId().getResourceId();
                        System.out.println("The uploaded file id: " +File_Completed_Id);
                        System.out.println("File URL: https://drive.google.com/open?id=" +File_Completed_Id);

                    }
                };
            }
                    );
        }

    }
    );
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多