[英]Android Google Drive API download files from app folder
如何從Google雲端硬盤中的“ 應用程序文件夾”下載設備上的文件 ? 該文件夾對用戶不可見,只有特定的應用程序可以使用它。
基本上,我需要在此文件夾中上傳多個文件(某些應用程序和用戶設置),然后再將其重新下載到設備上。 它就像某種形式的用戶數據備份。
我已經在App Folder中創建了文件,我可以這樣讀取它們:
DriveFile appFolderFile = driveApi.getFile(googleApiClient, driveId);
但是我不知道如何上傳現有文件,然后將那些文件下載到設備上的特定文件夾中。 我搜索了文檔,但沒有找到解決方案。
在文檔中,我發現了如何讀取和檢索文件內容,但是沒有有關下載文件本身的信息。
有人可以給我提示如何做嗎? 或者,也許我只是錯過了文檔中的正確部分,或者甚至不可能,而我必須使用REST API?
更新:
也許我弄錯了,下載文件內容和下載文件之間沒有區別?
要下載文件 ,請向文件的資源URL發出授權的HTTP GET
請求,並包含查詢參數alt=media
如下所示:
GET https://www.googleapis.com/drive/v3/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs
下載文件要求用戶至少具有讀取權限。 此外,您的應用必須具有允許讀取文件內容的范圍。 例如,使用
drive.readonly.metadata
范圍的應用將無權下載文件內容。 具有編輯權限的用戶可以通過將viewersCanCopyContent
字段設置為true來限制只讀用戶的下載。
使用Drive API執行文件下載的示例:
String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
.executeMediaAndDownloadTo(outputStream);
下載后,需要使用parent
參數將文件放入特定文件夾,然后在文件的parents
屬性中指定正確的ID。
例:
String folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
fileMetadata.setParents(Collections.singletonList(folderId));
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id, parents")
.execute();
System.out.println("File ID: " + file.getId());
檢查該線程 。
按照以下代碼獲取已保存在Google驅動器中的所有數據
public void retrieveContents(DriveFile file) {
Task<DriveContents> openFileTask =
getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>() {
@Override
public Task<Void> then(@NonNull Task<DriveContents> task) throws Exception {
DriveContents contents = task.getResult();
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");
}
Log.e("result ", builder.toString());
}
Task<Void> discardTask = MainActivity.this.getDriveResourceClient().discardContents(contents);
return discardTask;
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.