简体   繁体   English

如何使用Drive API下载Google Doc,电子表格和Presentation文件?

[英]How to download Google Doc, Spreadsheet and Presentation file by using Drive API?

I used the following Drive API code in Android for download files from Google Drive. 我在Android中使用以下Drive API代码从Google云端硬盘下载文件。

GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(GoogleDriveActivity.this);

DriveClient mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);

DriveResourceClient mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);

By using this code I am able to download all files ie Docx, Doc, Image, xls, xlsx, txt, pdf etc. 通过使用此代码,我可以下载所有文件,即Docx,Doc,Image,xls,xlsx,txt,pdf等。

but it has given the issue for the following files. 但是它为以下文件带来了问题。

Google Doc (application/vnd.google-apps.document), Google文件(application / vnd.google-apps.document),

SpreadSheet (application/vnd.google-apps.spreadsheet), SpreadSheet(application / vnd.google-apps.spreadsheet),

Presentation file (application/vnd.google-apps.presentation) 演示文件(application / vnd.google-apps.presentation)

even I tried to change metadata for the selected file by using this code but still, its shown file size is 0 (Zero) and the extension is null. 即使我尝试通过使用此代码来更改所选文件的元数据,但仍显示的文件大小为0(零),扩展名为null。

MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
            .setMimeType(Constants.MIME_TYPE_DOCX)
            .build();

Task<Metadata> updateMetadataTask =
            mDriveResourceClient.updateMetadata(file, changeSet);

So please suggest the solution if anybody implemented it. 因此,请提出解决方案(如果有人实施)。

I tried to download Google Doc, Spreadsheet and Presentation file by using Google Drive Android API but didn't get any proper solution for it by using Drive API. 我尝试通过使用Google Drive Android API下载Google Doc,电子表格和演示文稿文件,但没有通过Drive API获得任何适当的解决方案。

But I have read in many places that you can download this documents using REST. 但是我在许多地方都读过您可以使用REST下载此文档。 Finally, I got the right solution for it when I combined both these codes ie Drive API Code and REST code 最后,当我将这两个代码(即Drive API代码和REST代码)组合在一起时,我得到了正确的解决方案

Here is the code for it. 这是它的代码。

First, you need to add these two lines in your build.gradle file in App module. 首先,您需要在App模块的build.gradle文件中添加这两行。

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

Second, Initialize GoogleAccountCredential and Drive by your selected account. 其次,通过您选择的帐户初始化GoogleAccountCredential和云端硬盘。

private com.google.api.services.drive.Drive driveService = null;
private GoogleAccountCredential signInCredential;
private long timeStamp;
private String fileName;


// Initialize credentials and service object.
signInCredential = GoogleAccountCredential.usingOAuth2(
   getApplicationContext(), Arrays.asList(SCOPES))
   .setBackOff(new ExponentialBackOff());


 if (!TextUtils.isEmpty(signInAccount.getAccount().name)) {  
  signInCredential.setSelectedAccountName(signInAccount.getAccount().name);
  signInCredential.setSelectedAccount(new Account(signInAccount.getAccount().name, getPackageName()));
}

if (!TextUtils.isEmpty(signInCredential.getSelectedAccountName())) {
   HttpTransport transport = AndroidHttp.newCompatibleTransport();
   JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
   driveService = new com.google.api.services.drive.Drive.Builder(transport, jsonFactory, signInCredential)
           .setApplicationName(appName)
           .build();
}

//Pass two parameters ie fileId and mimeType which one you get when you select the file name. //传递两个参数,即fileId和mimeType,当选择文件名时会得到一个。

public void retrieveGoogleDocContents(String fileId, String mimeType) throws IOException {
   try {        

   File storageDir =createStorageDir();

   timeStamp = System.currentTimeMillis();
//selectedFileName which one you get when you select any file from the drive, or you can use any name.
   fileName = selectedFileName + "." +getFileExtension(mimeType);

   File localFile = new File(storageDir, timeStamp + "_" + fileName);
   if (!localFile.exists()) {
       if (localFile.createNewFile())
           Log.d(TAG, fileCreated);
   }


   AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {

       @Override
       protected void onPreExecute() {
           super.onPreExecute();
       }

       @Override
       protected Boolean doInBackground(Void... params) {

           boolean isSuccess = false;
           OutputStream outputStream = null;

           try {
               outputStream = new FileOutputStream(localFile);

               com.google.api.services.drive.Drive.Files.Export request = driveService.files().export(fileId,getFileMimeType(mimeType));
               request.getMediaHttpDownloader().setProgressListener(new GoogleDriveActivity.CustomProgressListener());
               request.getMediaHttpDownloader().setDirectDownloadEnabled(false);
               request.executeMediaAndDownloadTo(outputStream);

               isSuccess = true;

           } catch (UserRecoverableAuthIOException e) {
               Log.d(TAG, "REQUEST_AUTHORIZATION Called");
               startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
           } catch (IOException transientEx) {
               // Network or server error, try later
               Log.e(TAG, transientEx.toString());
           } finally {
              close(outputStream);
           }

           return isSuccess;
       }

       @Override
       protected void onPostExecute(Boolean isSuccess) {
           Log.i(TAG, "Download Successfully :" + isSuccess);           
                    }

   };
   task.execute();
   } catch (IOException e){
   Log.e(TAG, e.toString()); 
   }
 }

public static void close(Closeable c) {
   if (c == null) return;
   try {
       c.close();
   } catch (IOException e) {
       log.log(Level.SEVERE, e.getMessage(), e);
   }
}


public static File createStorageDir() {
   String path = Environment.getExternalStorageDirectory() + "/" + Constants.IMAGE_DIRECTORY;
   File storageDir = new File(path);
   if (!storageDir.exists()) {
       if (storageDir.mkdir())
           Log.d(TAG, "Directory created.");
       else
           Log.d(TAG, "Directory is not created.");
   } else
       Log.d(TAG, "Directory exist.");

   return storageDir;
}

Here are file mime type and extension. 这是文件mime类型和扩展名。

public final static String ICON_DOCX = "docx";
public final static String ICON_PPTX = "pptx";
public final static String ICON_XLSX = "xlsx";

public final static String MIME_TYPE_GOOGLE_DOC = "application/vnd.google-apps.document";
public final static String MIME_TYPE_GOOGLE_SPREADSHEET = "application/vnd.google-apps.spreadsheet";
public final static String MIME_TYPE_GOOGLE_PRESENTATION = "application/vnd.google-apps.presentation";
public final static String MIME_TYPE_DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
public final static String MIME_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public final static String MIME_TYPE_PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation";


public static String getFileExtension(String fileMimeType) {
   String fileExtension = Constants.ICON_PDF;

   if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_DOC))
       fileExtension = Constants.ICON_DOCX;
   else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_SPREADSHEET))
       fileExtension = Constants.ICON_XLSX;
   else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_PRESENTATION))
       fileExtension = Constants.ICON_PPTX;

   return fileExtension;
}

public static String getFileMimeType(String fileMimeType) {
   String newMimeType = Constants.MIME_TYPE_PDF;

   if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_DOC))
       newMimeType = Constants.MIME_TYPE_DOCX;
   else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_SPREADSHEET))
       newMimeType = Constants.MIME_TYPE_XLSX;
   else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_PRESENTATION))
       newMimeType = Constants.MIME_TYPE_PPTX;

   return newMimeType;
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM