2012-07-05 218 views
2

以下是使用Gdrive V2 sdk將文件上傳到特定文件夾的方法。 1)將文件插入根文件夾(Drive.Files.insert(File,AbstractInputStream) 2)刪除新上傳文件的根父引用 3)將特定目標文件夾添加爲文件的新父引用。Google Drive V2 Java API - 將文件上傳到特定文件夾

以上作品。 但是,如果網絡速度很慢,我們會在移到特定目標文件夾之前看到位於Root文件夾中的文件很長一段時間。我們如何避免這種情況?我們可以批量上述三種操作嗎?但AFAIK,批處理支持特定類型的操作,比如..我們只能批量所有文件操作或父操作或修訂操作。我們可以批量操作屬於不同的類型,例如(Files.insert()和Parent.delete())?

輸入將不勝感激。

謝謝!

回答

5

您可以通過在元數據中設置父項字段直接在指定文件夾中創建文件。

{ 
    "title" : "test.jpg", 
    "mimeType" : "image/jpeg", 
    "parents": [{ 
    "kind": "drive#file", 
    "id": "<folderId>" 
    }] 
} 

這是我在蟒蛇正在做的,但我相信有一個相關的Java編寫的。

+0

感謝埃裏克!這現在確實有效,我們早些時候嘗試過,現在沒有用。這就是爲什麼不得不採用三步法的原因。 – bipin

1

正如eric.f在他的回答中提到的,您需要爲文件設置父級

https://developers.google.com/drive/v2/reference/files/insert

import com.google.api.client.http.FileContent; 
import com.google.api.services.drive.Drive; 
import com.google.api.services.drive.model.File; 

import java.io.IOException; 
import java.util.Arrays; 
// ... 

public class MyClass { 

    // ... 

    /** 
    * Insert new file. 
    * 
    * @param service Drive API service instance. 
    * @param title Title of the file to insert, including the extension. 
    * @param description Description of the file to insert. 
    * @param parentId Optional parent folder's ID. 
    * @param mimeType MIME type of the file to insert. 
    * @param filename Filename of the file to insert. 
    * @return Inserted file metadata if successful, {@code null} otherwise. 
    */ 
    private static File insertFile(Drive service, String title, String description, 
     String parentId, String mimeType, String filename) { 
    // File's metadata. 
    File body = new File(); 
    body.setTitle(title); 
    body.setDescription(description); 
    body.setMimeType(mimeType); 

    // Set the parent folder. 
    if (parentId != null && parentId.length() > 0) { 
     body.setParents(
      Arrays.asList(new ParentReference().setId(parentId))); 
    } 

    // File's content. 
    java.io.File fileContent = new java.io.File(filename); 
    FileContent mediaContent = new FileContent(mimeType, fileContent); 
    try { 
     File file = service.files().insert(body, mediaContent).execute(); 

     // Uncomment the following line to print the File ID. 
     // System.out.println("File ID: %s" + file.getId()); 

     return file; 
    } catch (IOException e) { 
     System.out.println("An error occured: " + e); 
     return null; 
    } 
    } 

    // ... 
} 
相關問題