Google云端硬盘导入Google文档
问题描述:
我有以下代码来获取Google云端硬盘中文件的DriveContents
。我能够导入并获取MS Word,文本文件等的DriveContents
,但是当文件是Google(Google Doc,Google表格等)原生文件时,我无法获取内容。我的代码如下:Google云端硬盘导入Google文档
selectedFile.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
public void onResult(DriveApi.DriveContentsResult result) {
try {
if (!result.getStatus().isSuccess()) {
// display an error saying file can't be opened
Log.e(TAG, "Could not get file contents");
return;
}
// DriveContents object contains pointers
// to the actual byte stream
DriveContents contents = result.getDriveContents();
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
String contentsAsString = builder.toString();
contents.discard(getGoogleApiClient());
Log.i(TAG, contentsAsString);
} catch (Exception e) {
e.printStackTrace();
}
}
});
每当我收到了谷歌格式的文件,它只是返回一个结果是不是成功,并显示在我的日志中的错误。我怎样才能获得这些文件的文件内容?有什么特别的我应该做的?
我阅读下列文件:如果
答
不知道这是最好的解决办法,但我做到了下面的方法。我检查元数据,如果它是一个谷歌格式(文档,床单等),如果是,我有一个AsyncTask
,做以下:
// accountName is the email address the user used when choosing which account
String scope = "oauth2:https://www.googleapis.com/auth/drive.file";
token = GoogleAuthUtil.getTokenWithNotification(fragment.getActivity(), accountName, scope, null);
做好以上后,您可以使用获取文件API:
https://developers.google.com/drive/web/manage-downloads
从上述的token
给出关于下载的Authentication
头令牌。我们可以将文件导出为docx,pdf等,并以此方式下载。