2014-10-01 62 views
1

我想上傳一個文件到我的帳戶在谷歌驅動器。這個過程應該沒有人爲干預。有沒有辦法上傳一個文件在我的谷歌驅動器使用谷歌驅動器API提供我的用戶和我的密碼?在沒有OAuth的情況下將文件上傳到java驅動器

什麼我迄今所做的:

  • https://console.developers.google.com創建了一個項目,並啓用谷歌驅動API
  • https://console.developers.google.com - >的API &驗證 - >證書我創建了一個新的客戶端ID,在應用程序類型I中選擇服務帳戶,然後我下載了pkcs12密鑰。
  • 我有下面的代碼:

    /** 
    * Email of the Service Account 
    */ 
    private static final String SERVICE_ACCOUNT_EMAIL = "[email protected]"; 
    
    /** 
    * Path to the Service Account's Private Key file 
    */ 
    private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/path/to/pkcs12/donloaded.pkcs12"; 
    
    /** 
    * Build and returns a Drive service object authorized with the service 
    * accounts. 
    * 
    * @return Drive service object that is ready to make requests. 
    */ 
    public static Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException { 
        HttpTransport httpTransport = new NetHttpTransport(); 
        JacksonFactory jsonFactory = new JacksonFactory(); 
        List<String> scopes = new ArrayList<String>(); 
        scopes.add(DriveScopes.DRIVE); 
        GoogleCredential credential; 
        credential = new GoogleCredential.Builder() 
          .setTransport(httpTransport) 
          .setJsonFactory(jsonFactory) 
          .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) 
          .setServiceAccountScopes(scopes) 
          .setServiceAccountPrivateKeyFromP12File(new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH)) 
          .build(); 
        Drive service = new Drive.Builder(httpTransport, jsonFactory, null) 
          .setHttpRequestInitializer(credential).build(); 
        return service; 
    } 
    
    public static void main(String[] args) throws GeneralSecurityException, IOException, URISyntaxException { 
    
        Drive client = getDriveService(); 
    
        File body = new File(); 
        body.setTitle("mytitle"); 
        body.setMimeType("application/vnd.google-apps.spreadsheet"); 
    
        File file = client.files().insert(body).execute(); 
    
        System.out.println(file.getId()); 
        System.out.println(file.getAlternateLink()); 
    } 
    

當我運行代碼的結果是正確的,我得到的文件的id和備用鏈路,但該文件無法加載到我的帳戶。我將備用鏈接粘貼到瀏覽器中,但我沒有權限。

哪裏文件剛上載?我應該更改什麼以表明直至我的帳戶驅動器?我應該在哪裏添加我的用戶名和密碼才能與我的驅動器相關聯?我應該怎麼做文件才能公開?

非常感謝你爲你的全部注意力。我希望他們能幫助我。

回答

1

您還需要使它們看起來有人在「我的雲端硬盤」空間設置關於該項目的家長,如「根」。作爲父級的「根」是用戶界面中的「我的雲端硬盤」。

使用搜索在Drive UI確認,你會發現他們已上傳,但目前在一個名爲「unparented」,因爲您的代碼不添加父狀態。

1

您將文件上傳到您的服務帳戶。 如果您需要訪問該文件,它必須與您的電子郵件共享。 使用以下方法與您的電子郵件共享文件。

public static void shareFileOrFolder(Drive service, File file) 
     throws IOException { 
    Permission newPermission = new Permission(); 

    newPermission.setEmailAddress("[email protected]"); 
    newPermission.setValue("[email protected]"); 
    newPermission.setType("user"); 
    newPermission.setRole("writer"); 
    service.permissions().insert(file.getId(), newPermission).execute(); 
} 
相關問題