如何从android上传文件到谷歌驱动器

时间:2014-02-05 06:10:00

标签: android google-drive-api

我花了一天多的时间但没有得到任何可行的解决方案,可以让我上传/下载文件到Google Drive

我试过Google Play Service,但我找不到任何上传/下载文件的方法。

我尝试了Google客户端库,但有些方法尚未解决。

如:

service.files().insert(body, mediaContent).execute();
errors: The method execute() is undefined for the type Drive.Files.Insert

我可以通过以下代码上传图片,但这是Google云端硬盘文件加载程序。我一次只能上传一个文件。

mFile = new java.io.File(fileList.get(i));
                Log.i(TAG, "Creating new contents.");
                Drive.DriveApi.newContents(mGoogleApiClient).addResultCallback(
                        new OnNewContentsCallback() {

                            @Override
                            public void onNewContents(ContentsResult result) {

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

                                Log.i(TAG, "New contents created.");

                                OutputStream outputStream = result
                                        .getContents().getOutputStream();

                                byte[] byteStream = new byte[(int) mFile
                                        .length()];
                                try {
                                    outputStream.write(byteStream);
                                } catch (IOException e1) {
                                    Log.i(TAG, "Unable to write file contents.");
                                }

                                MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                                        .setMimeType("image/jpeg")
                                        .setMimeType("text/html")
                                        .setTitle("Android Photo.png").build();
                                // Create an intent for the file chooser, and
                                // start it.
                                IntentSender intentSender = Drive.DriveApi
                                        .newCreateFileActivityBuilder()
                                        .setInitialMetadata(metadataChangeSet)
                                        .setInitialContents(
                                                result.getContents())
                                        .build(mGoogleApiClient);
                                try {
                                    mActivity.startIntentSenderForResult(
                                            intentSender, REQUEST_CODE_CREATOR,
                                            null, 0, 0, 0);
                                    publishProgress(1);
                                } catch (SendIntentException e) {
                                    Log.i(TAG, "Failed to launch file chooser.");
                                    publishProgress(0);
                                }
                            }
                        });

但仍在争取下载文件。

5 个答案:

答案 0 :(得分:3)

大家好我得到了解决方案。我们绝不应该使用Android API进行完整的云端硬盘访问。我们应该致力于纯Java代码,因为Google也表示要访问Drive以便广泛访问使用java库。

我删除了与Google Play服务相关的所有代码。我现在正在使用完全使用java,轻松上传,删除,编辑,下载我想要的任何东西。

Google doc还没有提供有关Android驱动程序的详细说明,而在使用Java库时,您可以获得已经创建的方法等等。

我没有提供任何代码,但是对于我或对Drive完全访问感兴趣的其他人使用基于Java的代码。

答案 1 :(得分:0)

将文件上传到Google云端硬盘

Drive.Files.Insert insert;
try {
    final java.io.File uploadFile = new java.io.File(filePath);
    File fileMetadata = new File();
    ParentReference newParent = new ParentReference();
    newParent.setId(upload_folder_ID);
    fileMetadata.setParents(
            Arrays.asList(newParent));
    fileMetadata.setTitle(fileName);
    InputStreamContent mediaContent = new InputStreamContent(MIMEType, new BufferedInputStream(
                new FileInputStream(uploadFile) {
                    @Override
                    public int read(byte[] buffer,
                            int byteOffset, int byteCount)
                            throws IOException {
                        // TODO Auto-generated method stub
                        Log.i("chauster","progress = "+byteCount);
                        return super.read(buffer, byteOffset, byteCount);
                    }
                }));
            mediaContent.setLength(uploadFile.length());
    insert = service.files().insert(fileMetadata, mediaContent);
    MediaHttpUploader uploader = insert.getMediaHttpUploader();
    FileUploadProgressListener listener = new FileUploadProgressListener();
    uploader.setProgressListener(listener);
    uploader.setDirectUploadEnabled(true);
    insert.execute();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

public class FileUploadProgressListener implements MediaHttpUploaderProgressListener {

    @SuppressWarnings("incomplete-switch")
    @Override
    public void progressChanged(MediaHttpUploader uploader) throws IOException {
        switch (uploader.getUploadState()) {
            case INITIATION_STARTED:
                break;
            case INITIATION_COMPLETE:
                break;
            case MEDIA_IN_PROGRESS:
                break;
            case MEDIA_COMPLETE:
                break;
        }
    }
}

从谷歌驱动器下载文件this

答案 2 :(得分:0)

Google SDK 现在对Android友好。有一个完整的访问范围,您可以轻松访问列表和阅读所有驱动器文件,并且可以轻松地在Android应用中使用,因为我们的newer client library适合Android使用!我还建议您观看Google IO的演讲,其中介绍了如何将移动应用与云端硬盘进行整合

图书馆可以更轻松地进行身份验证

 /** Authorizes the installed application to access user's protected data. */
  private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(CalendarSample.class.getResourceAsStream("/client_secrets.json")));
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, JSON_FACTORY, clientSecrets,
        Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
        .build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  } 

该库在Google App Engine上运行

媒体上传

class CustomProgressListener implements MediaHttpUploaderProgressListener {
  public void progressChanged(MediaHttpUploader uploader) throws IOException {
    switch (uploader.getUploadState()) {
      case INITIATION_STARTED:
        System.out.println("Initiation has started!");
        break;
      case INITIATION_COMPLETE:
        System.out.println("Initiation is complete!");
        break;
      case MEDIA_IN_PROGRESS:
        System.out.println(uploader.getProgress());
        break;
      case MEDIA_COMPLETE:
        System.out.println("Upload is complete!");
    }
  }
}

File mediaFile = new File("/tmp/driveFile.jpg");
InputStreamContent mediaContent =
    new InputStreamContent("image/jpeg",
        new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());

Drive.Files.Insert request = drive.files().insert(fileMetadata, mediaContent);
request.getMediaHttpUploader().setProgressListener(new CustomProgressListener());
request.execute();

您还可以使用可恢复的媒体上传功能,而无需使用特定于服务的生成库。这是一个例子:

File mediaFile = new File("/tmp/Test.jpg");
InputStreamContent mediaContent =
    new InputStreamContent("image/jpeg",
        new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());

MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, transport, httpRequestInitializer);
uploader.setProgressListener(new CustomProgressListener());
HttpResponse response = uploader.upload(requestUrl);
if (!response.isSuccessStatusCode()) {
  throw GoogleJsonResponseException(jsonFactory, response);
}

答案 3 :(得分:0)

经过几天寻找一个好例子,我发现Google I/O app on GitHub具有很好的实用工具方法,可以从云端硬盘创建,更新和读取文件。

答案 4 :(得分:0)

我也尝试过此方法,我在寻找将用户数据上传到自己帐户的教程。但是我什么也没找到。 Google建议使用Google Firebase存储而非Google驱动器。如果您认为,WhatsApp如何使用Google Drive上载数据。然后我的回答是,谷歌为WhatsApp提供特殊服务。因此,使用Firebase存储,既简单又便宜,并且也进行了更新。使用文档可以非常正确地使用它们。这些文档真的很棒。