簡體   English   中英

如何將文件從 android 上傳到谷歌驅動器

[英]How do I upload file to google drive from android

我花了一天多的時間,但沒有得到任何可行的解決方案,讓我可以將文件上傳/下載到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 Drive 文件上傳器。 我一次只能上傳一個文件。

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

但仍在爭取下載文件。

我得到了解決方案。 我們永遠不應該使用 Android API 來獲得完整的 Drive 訪問權限。 我們應該使用純 Java 代碼,因為 Google 還說要訪問 Drive 以進行廣泛訪問,請使用 Java 庫。

我刪除了與 Google Play 服務相關的所有代碼。 我現在完全使用java,可以輕松上傳、刪除、編輯、下載我想要的所有內容。

另一件事谷歌文檔沒有提供關於 android api 的谷歌驅動器的詳細描述,而在 java 庫上工作時,你可以獲得已經創建的方法等等。

我沒有提供任何代碼,而是說對於我或對 Drive 完全訪問感興趣的其他人使用基於 Java 的代碼。

將文件上傳到 Google Drive

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

並從谷歌驅動器下載文件看這個

Google SDK現在對安卓友好。 有一個完全訪問范圍,可讓您訪問列出和讀取所有驅動器文件,並且可以輕松地在 Android 應用程序中使用,因為我們的新客戶端庫對Android 友好! 我還推薦觀看來自 Google IO 的這個演講,它解釋了如何將移動應用程序與 Drive 集成

該庫使身份驗證更容易

 /** 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);
}

經過幾天尋找一個好例子,我發現GitHub上Google I / O應用程序具有很好的實用程序方法,可以從Drive創建,更新和讀取文件。

我也試過這個,我正在尋找教程將一些用戶數據上傳到他們自己的帳戶。 但我沒有發現任何東西。 Google 建議使用 google firebase storage 而不是 google drive。 如果您想,WhatsApp 如何使用谷歌驅動器上傳數據。 那么我的答案是谷歌為WhatsApp提供了特殊服務。 所以使用 firebase 存儲,它既簡單又便宜,而且還更新了。 使用文檔可以非常正確地使用它們。 文檔真的很棒。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM