简体   繁体   中英

Java Google Api [Service account]

I am not able to upload files to a specific drive folder.

My Java code is:

HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    try {
        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(IRingeeConstants.SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(Collections.singleton(DriveScopes.DRIVE_APPDATA)).setServiceAccountPrivateKeyFromP12File(new java.io.File("G:\\Ringee-1a1f1b786226.p12")).build();

        Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName(IRingeeConstants.APPLICATION_NAME).build();

        File body = new File();
        body.setTitle("ringee");
        body.setDescription("ringeeapp");
        body.setMimeType("application/vnd.google-apps.folder");
        java.io.File fileContent = new java.io.File("G:\\document.txt");
        FileContent mediaContent = new FileContent("text/plain", fileContent);

        File file = service.files().insert(body, mediaContent).execute();
        System.out.print("file id is :" + file.getId());
        Permission newPermission = new Permission();
        // for showing files in browser that reason only using additional
        // permission
        newPermission.setValue(IRingeeConstants.USER_ACCOUNT_EMAIL);
        newPermission.setType("owner");
        newPermission.setRole("writer");
        service.permissions().insert(file.getId(), newPermission).execute();
        getFileByFileId(service, file.getId());
    } catch (Exception e) {
        e.printStackTrace();
    }

Files are uploaded in root folder. Why is this?

How to solve this problem..

With in Google drive Parents is the folder name.

By default files are placed in the root directory. If you run files.list or try it at the bottom you get a list of all the files on your Google drive.

Files with a mimetype of application/vnd.google-apps.folder are directories.

{

   "kind": "drive#file",
   "id": "0B5pJkOVaKccEfjVaajNvRFNTa3pRZ2NlUmFWTjczaGpjaHE1NFo5bWFBWTJPOGU2TGtOTzA",     
   "title": "AppScripts",
   "mimeType": "application/vnd.google-apps.folder",
   "parents": [
    {    
     "kind": "drive#parentReference",
     "id": "0AJpJkOVaKccEUk9PVA",

     "parentLink": "https://www.googleapis.com/drive/v2/files/0AJpJkOVaKccEUk9PVA",
     "isRoot": true
    }

Above you see my AppScripts directory on my google drive. If you see the isRoot under parents you can tell that it is in the root directory

  {

   "kind": "drive#file",
   "id": "0B1bbSFgVLpoXcEhfVDRFRF8tTkU",
   "title": "GDE-app-team",
   "mimeType": "application/vnd.google-apps.folder",
   "parents": [
    {
     "kind": "drive#parentReference",
     "id": "0B_UBp7FcUna-NU5abkhxYWVocTA",
     "selfLink": "https://www.googleapis.com/drive/v2/files/0B1bbSFgVLpoXcEhfVDRFRF8tTkU/parents/0B_UBp7FcUna-NU5abkhxYWVocTA",
     "parentLink": "https://www.googleapis.com/drive/v2/files/0B_UBp7FcUna-NU5abkhxYWVocTA",
     "isRoot": false
    }

Above you see my GDE-app-team directory if you notice it has isRoot set to false it is not in the root directory. The directory it is in is 0B_UBp7FcUna-NU5abkhxYWVocTA I would have to do a files.get on that id to find the name of the direcroy that GDE-app-team is in.

 "kind": "drive#file",
 "id": "0B_UBp7FcUna-NU5abkhxYWVocTA",
 "etag": "\"WsLEI6l9KW9DlzjU9lm9xLuMVm8/MTQwOTkyOTg4Njc0Mw\"",
 "selfLink": "https://www.googleapis.com/drive/v2/files/0B_UBp7FcUna-NU5abkhxYWVocTA",
 "alternateLink": "https://docs.google.com/folderview?id=0B_UBp7FcUna-NU5abkhxYWVocTA&usp=drivesdk",
 "iconLink": "https://ssl.gstatic.com/docs/doclist/images/icon_11_shared_collection_list_1.png",
 "title": "GDE",

You need to add parent id to the body

parentId Optional parent folder's ID.

I am not a java expert but from the documentation its something like this :

 body.setParents(Arrays.asList(new ParentReference().setId(parentId)));

I normally do a files list with q to search for all the directories

mimeType = 'application/vnd.google-apps.folder'

That should give you back the file ID you will need to add to the parents.

Here is a code snippet get creates a file in parent's directory. The parent's directory ID can be obtained from search by name, mime, ...

The Github example I'm pointing to has a full CRUD wrapper for both the REST (the one you are using) and the GDAA APIs.

Be careful though, in Google Drive, the file/folder name is only a metadata field. ie you may have multiple folders/files with the same name in the same location (folder). Only the ID (sometimes called Resource Id) is unique. This means that if you have a folder name and perform search, better check if you got only one object - the correct one (checking its parent id, mime type, ...). Basically your full logic has to take it in account.

Hope it helps, Good Luck.

A little late to answer but following is a simple method that uploads files to Google Drive provided that you have the credentials available. The logic for getting authorization can be written in another function which in the following case is authorize() . Also, I'm using a global Drive instance since the following method is among many.

public static String insertFile(String folderId, java.io.File file) throws IOException, GeneralSecurityException {
    System.out.println("Uploading file " + file.getName() + " to Google Drive");
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    // authorization
    Credential credential = authorize(); // Get authorization

    // set up the global Drive instance
    drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential)
            .setApplicationName("YourAppName")
            .build();

    File fileMetadata = new File();
    fileMetadata.setName(file.getName());
    FileContent mediaContent = new FileContent("put/mime/type/here", file);

    File uploadedFile;
    if (folderId != null && !folderId.isEmpty()) {
        fileMetadata.setParents(Collections.singletonList(folderId));
        uploadedFile = drive.files()
                .create(fileMetadata, mediaContent)
                .setFields("id, parents")
                .execute();
    } else {
        uploadedFile = drive.files()
                .create(fileMetadata, mediaContent)
                .setFields("id")
                .execute();
    }

    return uploadedFile == null ? null : uploadedFile.getId();
}

The above method takes in the folderId and the file to be uploaded as parameters and returns the fileId if it is successfully uploaded.

If you pass null or an empty string into folderId , then the file is uploaded in the root directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM