我在Android中使用以下Drive API代码从Google云端硬盘下载文件。
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setMimeType(Constants.MIME_TYPE_DOCX)
.build();
Task<Metadata> updateMetadataTask =
mDriveResourceClient.updateMetadata(file, changeSet);
通过使用此代码,我可以下载所有文件,即Docx,Doc,Image,xls,xlsx,txt,pdf等。
但是它给出了以下文件的问题。
Google Doc(application / vnd.google-apps.document),
SpreadSheet(application / vnd.google-apps.spreadsheet),
演示文稿文件(application / vnd.google-apps.presentation)
即使我尝试使用此代码更改所选文件的元数据,但仍然显示文件大小为0(零)并且 扩展名为null。
{{1}}
因此,如果有人实施,请建议解决方案。
答案 0 :(得分:0)
我尝试使用Google云端硬盘Android API下载Google文档,电子表格和演示文稿文件,但未使用Drive API获得任何正确的解决方案。
但我在很多地方都读过你可以使用REST下载这些文件。最后,当我将这两个代码组合起来时,我得到了正确的解决方案,即Drive API Code和REST code
以下是代码。
首先,您需要在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'
}
其次,按所选帐户初始化GoogleAccountCredential和Drive。
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();
}
//传递两个参数,即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;
}
这是文件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;
}