简体   繁体   English

GDAA(Google Drive Android API):使用fileId从AppDataFolder下载文件

[英]GDAA(Google Drive Android API): download file from AppDataFolder by using fileId

I'm using google drive in my app. 我在我的应用程序中使用Google Drive。 I'm able to upload data in Google drive App folder and getting the file id. 我可以在Google drive App folder上传数据并获取文件ID。 My Question is, how to download it from appDataFolder by using FileId This is how i'm getting the file ids 我的问题是,如何使用FileIdappDataFolder下载它这是我获取文件ID的方式

     private List<String> getDataFromApi() throws IOException {

        List<String> fileInfo = new ArrayList<String>();
        FileList lst = mService.files().list()
                .setSpaces("appDataFolder")
                .execute();

        FileList result = mService.files().list()
                .setSpaces("appDataFolder")
                .setFields("nextPageToken, files(id, name, mimeType)")
                .execute();
        List<File> files = result.getFiles();
        if (files != null) {
            for (File file : files) {
                fileInfo.add(String.format("%s (%s) %s\n",
                        file.getName(), file.getId(), file.getMimeType()));
            }
        }
        return fileInfo;
    }

I'm using v3 of google drive services. 我正在使用v3的Google驱动器服务。

compile('com.google.apis:google-api-services-drive:v3-rev102-1.23.0') {
    exclude group: 'org.apache.httpcomponents'
}

Thanks In Advance 提前致谢

Finally I got My answer. 终于我得到了答案。 Hope this will help to others also for downloading from appDataFolder . 希望这对从appDataFolder下载的其他人也有帮助。 Here I'm downloading and saving the file into SD card folder name Spectors . 在这里,我将文件下载并保存到SD card文件夹名称Spectors And passing the value of File type of com.google.api.services.api.drive.model.File . 并传递com.google.api.services.api.drive.model.File的File类型的值。

       private void downloadFile(boolean useDirectDownload, File uploadedFile)
            throws IOException {


        java.io.File direct = new java.io.File(Environment.getExternalStorageDirectory()
                + "/Spectors");
        if (!direct.exists()) {
            direct.mkdirs();
        }

        java.io.File parentDir = new java.io.File(direct.getAbsolutePath());
        if (!parentDir.exists() && !parentDir.mkdirs()) {
            throw new IOException("Unable to create parent directory");
        }
        OutputStream out = new FileOutputStream(new java.io.File(parentDir, uploadedFile.getName()+".zip"));
        com.google.api.services.drive.Drive.Files.Get files = mService.files().get(uploadedFile.getId());
        files.executeMediaAndDownloadTo(out);

        Log.e(TAG, "downloadFile:2 " + files.toString() + "\n"+uploadedFile.getFileExtension() );
}

you can also apply following approach to download the content from app folder 您还可以采用以下方法从app文件夹下载内容

get files from app folder by the following code 通过以下代码从应用程序文件夹中获取文件

private void listFiles() {
    Query query =
            new Query.Builder()
                    .addFilter(Filters.or(Filters.eq(SearchableField.MIME_TYPE, "text/html"),
                            Filters.eq(SearchableField.MIME_TYPE, "text/plain")))
                    .build();
    getDriveResourceClient()
            .query(query)

            .addOnSuccessListener(this,

                    new OnSuccessListener<MetadataBuffer>() {
                        @Override
                        public void onSuccess(MetadataBuffer metadataBuffer) {
                            //mResultsAdapter.append(metadataBuffer);

                            for (int i = 0; i <metadataBuffer.getCount() ; i++) {
                                retrieveContents(metadataBuffer.get(i).getDriveId().asDriveFile());
                            }
                        }
                    }

            )
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e(TAG, "Error retrieving files", e);
                    MainActivity.this.finish();
                }
            });

}

to download the content the the following code 下载内容如下代码

 private void retrieveContents(DriveFile file) {
        // [START drive_android_open_file]
        Task<DriveContents> openFileTask =
                getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
        // [END drive_android_open_file]
        // [START drive_android_read_contents]
        openFileTask
                .continueWithTask(task -> {
                    DriveContents contents = task.getResult();
                    // Process contents...
                    // [START_EXCLUDE]
                    // [START drive_android_read_as_string]
                    try (BufferedReader reader = new BufferedReader(
                                 new InputStreamReader(contents.getInputStream()))) {
                        StringBuilder builder = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            builder.append(line).append("\n");
                        }
                        showMessage(getString(R.string.content_loaded));
                        mFileContents.setText(builder.toString());
                    }
                    // [END drive_android_read_as_string]
                    // [END_EXCLUDE]
                    // [START drive_android_discard_contents]
                    Task<Void> discardTask = getDriveResourceClient().discardContents(contents);
                    // [END drive_android_discard_contents]
                    return discardTask;
                })
                .addOnFailureListener(e -> {
                    // Handle failure
                    // [START_EXCLUDE]
                    Log.e(TAG, "Unable to read contents", e);
                    showMessage(getString(R.string.read_failed));
                    finish();
                    // [END_EXCLUDE]
                });
        // [END drive_android_read_contents]
    }

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

相关问题 使用GDAA(适用于Android的Google Drive Api)创建/编辑/检索数据库文件 - Create / Edit / Retrieve DB file with GDAA (Google Drive Api for Android) Android,如何从Google云端硬盘文件选择器获取“ fileID” - Android, how to get “fileID” from Google Drive File picker 新的Google Drive Android API(GDAA)创建的文件未显示 - Files created by the NEW Google Drive Android API (GDAA) not showing up Google Drive Android API(GDAA)getResourceId()返回null(计时问题) - Google Drive Android API (GDAA) getResourceId() returning null (timing issue) 在 Android Studio 中使用 Google Drive API 从驱动器下载文件以上传到另一个驱动器 - Download file from drive to upload into another drive using Google Drive API in Android Studio 无法从Drive rest Api中的Google Drive获取所选文件的fileId - Can't get fileId of selected file from google drive in Drive rest Api 如何使用Drive.API从Google云端硬盘下载文件? - How to download file from Google Drive using Drive.API? Google Drive API v3:从Android内容URI获取FileID - Google Drive API v3: get FileID from Android content URI 如何强制Android应用程序仅使用某个帐户来使用Google Drive API(GDAA)? - How can I force an android app to use only a certain account to use google drive api (GDAA)? 下载适用于Google Drive API Android的数据库文件 - Download database File For Google Drive API Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM