Uploading a File to Google Drive in Java

Jump boot awarding can be integrated to Google Drive APIs for all type of file operations using Google Drive Java client library. Google Drive API allows us to manage files and folders in Google Drive programmatically. In his article we will perform Google Drive integration in jump boot application, in which we volition integrate all possible operations for list, searching, upload, download etc.

Google Bulldoze API supports direct HTTP requests and customer library requests, all Google Bulldoze file operations search, find, upload, download, create folder, list binder are accessible from both these methods. Google Bulldoze API supports queries and special mime types to perform files and folders operations.

Google Bulldoze Java client

The Coffee Client Library for Google API provides functionality common to all Google APIs like mistake treatment, HTTP transport, JSON parsing, authentication and media download/upload. The Java Client library includes a powerful OAuth ii.0 library with a lightweight, consistent interface, efficient JSON and XML data models that back up every type of data schema and protocol buffers.

To use Google APIs in Java, you would apply the generated Java library for the Google APIs. This generated client libraries include the API-specific information such as root URL along with the core google-API-coffee-customer. These libraries also include classes that represent entities for the API context, which are useful for making conversions between Java objects and JSON objects.

Google Bulldoze API Gradle dependency

Google periodically publishes its dependencies for different programming languages. For Gradle project, y'all can use following the Gradle dependencies :

compile 'com.google.API-client:google-API-client:1.23.0' compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0' compile 'com.google.APIs:google-API-services-drive:v3-rev110-i.23.0'

Google drive v3 Java client integration with Spring boot

Following are the steps to integrate Google Drive v3 API's Java client with Spring boot application.

ane. Enable Google Bulldoze APIs

You need a Google account, on which you tin enable Google Drive APIs. Visit Google's Java QuickStart page, in case you accept multiple Google login and so switch to the Google account on which y'all desire to enable Google Drive APIs. Click on the push button "Enable the Drive API", a Popup window will open as shown below.

Enable Google Drive API
Enable Google Drive API

two. Download Google drive project credentials

The Google drive popup will show a suggested proper noun as QuickStart, yous can employ this name or change it and click the next button. In the next window, a drop-downwardly will be shown, select the "Desktop app" selection for the Java client library. Side by side window volition testify the credentials, download the file from here, this file volition have default name as "credentials.json".

Download crendentials for Google Drive API
Download crendentials for Google Drive API

three. Java Gradle Project setup

Spring boot Gradle project is recommended for this integration, as information technology volition remove lots of average code. Visit the page for leap boot initializer and create a Gradle projection with Java 11.

four. Add Google bulldoze credentials and dependencies in Leap boot projection

Open up the Spring boot project in any IDE (Intellij Thought is recommended) and import the projection as Gradle project. One time project import is complete, nether resources directory, add your file "credentials.json". In the build.gradle file, add together all three Gradle dependencies for Google Drive customer libraries and click the import push.

5. Configure Google drive API scopes

Google Drive has different kinds of permissions which are divided into a few categories, these categories are called scopes. Yous can combine i or more than scopes together too. Since we need to perform every type of operation in Google Drive, and so in our instance we will employ scope "DRIVE".

Google drive API scopes Purpose
DRIVE View and manage the files in your Google Drive.
DRIVE_APPDATA View and manage its own configuration information in your Google Drive.
DRIVE_FILE View and manage Google Bulldoze files and folders that you have opened or created with this app.
DRIVE_METADATA View and manage metadata of files in your Google Drive.
DRIVE_METADATA_READONLY View metadata for files in your Google Drive.
DRIVE_PHOTOS_READONLY View the photos, videos and albums in your Google Photos.
DRIVE_READONLY View the files in your Google Drive.
DRIVE_SCRIPTS Modify your Google Apps Script'Due south behavior.

6. Allow Google Drive Api access for offset time

Using credentials.json file, Google client library creates a URL with callback URL and prints into the console logs of the projection. You need to open up this URL in the browser and allow the access at least i time. By default, customer library start a jetty server at 8080 port which will listen to the callback when you open the URL in the browser. If you desire to modify the port or host in callback URL then yous can change it like post-obit:

LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost("127.0.0.i").setPort(8089).build();

7. Access tokens saved automatically in leap kicking projection

Once you grant access to Google Drive API, and then Google Client library automatically listens to information technology and saves the admission tokens into your project root directory nether a binder "tokens". Next time if you run the project, it will not enquire you to perform this step over again, as access tokens will be already present there. If you delete this admission token file, and so on server startup yous volition exist asked to perform the previous footstep over again.

8. Google Bulldoze API client case creation

Next stride is to combine everything and create a Google Drive API client instance, which volition be used to perform every file/folder operation. Bulldoze course is the service class which supports all operations on Google Drive.

In the post-obit instance, we have created a GoogleDriveManager class, which has one method getInstance() which returns the instance of Drive. We will utilize this class in all examples to get the drive connectedness.

@Service public grade GoogleDriveManager {    private static final String APPLICATION_NAME = "Technicalsand.com - Google Bulldoze API Java Quickstart";   individual static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();   individual static last String TOKENS_DIRECTORY_PATH = "tokens";   private static concluding List<String> SCOPES = Collections.singletonList(DriveScopes.Drive);   individual static final String CREDENTIALS_FILE_PATH = "/credentials.json";    public Bulldoze getInstance() throws GeneralSecurityException, IOException {      // Build a new authorized API customer service.      final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();      Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))            .setApplicationName(APPLICATION_NAME)            .build();      return service;    }    /**    * Creates an authorized Credential object.    *    * @param HTTP_TRANSPORT The network HTTP Transport.    * @return An authorized Credential object.    * @throws IOException If the credentials.json file cannot be found.    */   private Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {      // Load client secrets.      InputStream in = GoogleDriveManager.grade.getResourceAsStream(CREDENTIALS_FILE_PATH);      if (in == zippo) {         throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);      }      GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));       // Build flow and trigger user authorization request.      GoogleAuthorizationCodeFlow menstruum = new GoogleAuthorizationCodeFlow.Architect(            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)            .setDataStoreFactory(new FileDataStoreFactory(new coffee.io.File(TOKENS_DIRECTORY_PATH)))            .setAccessType("offline")            .build();      LocalServerReceiver receiver = new LocalServerReceiver.Architect().setHost("127.0.0.i").setPort(8089).build();       render new AuthorizationCodeInstalledApp(flow, receiver).qualify("user");   }  }

Google Drive list files using Coffee client

Google Bulldoze identifies every object (file or folder) using its unique id. If we don't specify any parentId so Google Bulldoze performs the functioning on the unabridged Google Drive and list of every file/folder irrespective of its parent folder. Listing of files supports pagination from where y'all tin can control the number of results in a single API hit.

In the following example, nosotros want to list the content of the whole Google Drive using pagination size 10. Yous will see it returns the results irrespective of Google Bulldoze parent folder.

// FileManager.java public List<File> listEverything() throws IOException, GeneralSecurityException {   // Print the names and IDs for upwards to 10 files.   FileList result = googleDriveManager.getInstance().files().listing()         .setPageSize(10)         .setFields("nextPageToken, files(id, name)")         .execute();   return effect.getFiles(); }  // MainController.java @GetMapping({"/"}) public ResponseEntity<Listing<File>> listEverything() throws IOException, GeneralSecurityException {   List<File> files = fileManager.listEverything();   return ResponseEntity.ok(files); }

Google Drive listing files in binder using Java client

Google Drive API allows you to search for a specific gear up of folders or files under a folder. It supports query String "q" at file list level to filter the results.

The format of a query string for Google Drive is: query_term operator values

  • First Instance: 'folderId' in parents
  • Second Instance: 'root' in parents
  • Third Example: mimeType='image/jpeg'

Start instance query volition impress all the files and folders nowadays under the folder which has this id. If you want to print files/folders nowadays at the summit level of Google bulldoze and then instead of folderId, mention it as root. If you specify the mimeType in the query then only the matching files will be shown in results.

In the post-obit case code, nosotros desire the endpoint "/list" to print all the files/folders present at the root level of Google Drive (not at nested level). Output of this api will list every file/binder name with its id. For any folder, employ its id in the api endpoint as  "/list/folderid/ so you will see the content of that item folder.

// FileManager.coffee public Listing<File> listFolderContent(String parentId) throws IOException, GeneralSecurityException {   if(parentId == nil){      parentId = "root";   }   Cord query = "'" + parentId + "' in parents";   FileList issue = googleDriveManager.getInstance().files().list()         .setQ(query)         .setPageSize(ten)         .setFields("nextPageToken, files(id, name)")         .execute();   return result.getFiles(); }  // MainController.java @GetMapping({"/list","/list/{parentId}"}) public ResponseEntity<Listing<File>> listing(@PathVariable(required = false) String parentId) throws IOException, GeneralSecurityException {   List<File> files = fileManager.listFolderContent(parentId);   return ResponseEntity.ok(files); }

Google Drive check if folder exists using Coffee client

To search for a folder past name in Google Drive, you need to use mimeType "application/vnd.google-apps.folder" in the query. To search folder at whatsoever level in Google Bulldoze, in query role use root equally "'root' in parents", if you want to search a folder under specific folder so query should be "'parentId' in parents", where parentId is id of parent folder under which folder needs to exist searched. Utilize a loop over pagination for results until all results are processed and compared with name.

In the following example, if a folder is establish via proper noun then its folder id is returned. In case the folder is not present, then binder id is nix in response.

individual String searchFolderId(String folderName, Bulldoze service) throws Exception {   return searchFolderId(null, String folderName, Bulldoze service); }  private Cord searchFolderId(String parentId, String folderName, Drive service) throws Exception {   String folderId = null;   String pageToken = zippo;   FileList event = nil;    File fileMetadata = new File();   fileMetadata.setMimeType("application/vnd.google-apps.folder");   fileMetadata.setName(folderName);    do {      String query = " mimeType = 'awarding/vnd.google-apps.binder' ";      if (parentId == zilch) {         query = query + " and 'root' in parents";      } else {         query = query + " and '" + parentId + "' in parents";      }      upshot = service.files().list().setQ(query)            .setSpaces("drive")            .setFields("nextPageToken, files(id, name)")            .setPageToken(pageToken)            .execute();       for (File file : result.getFiles()) {         if (file.getName().equalsIgnoreCase(folderName)) {            folderId = file.getId();         }      }      pageToken = issue.getNextPageToken();   } while (pageToken != null && folderId == aught);    render folderId; }

Google Drive create folder if non exists using Java client

In Google Drive, yous can create a folder if it does not exist. Google Bulldoze Client library provides a "create" method, which accepts file'southward metadata class "File". In fileMetadata, you need to prepare mime-blazon, name of folder and optional parent binder id (if required). Once y'all call execute method on create method your binder gets created in Google Bulldoze.

Following code snippet shows how y'all tin create a folder if it does non be in Google Drive.

private String findOrCreateFolder(String parentId, String folderName, Drive driveInstance) throws Exception {   Cord folderId = searchFolderId(parentId, folderName, driveInstance);   // Folder already exists, so return id   if (folderId != null) {      render folderId;   }   //Folder dont exists, create it and return folderId   File fileMetadata = new File();   fileMetadata.setMimeType("application/vnd.google-apps.folder");   fileMetadata.setName(folderName);     if (parentId != null) {      fileMetadata.setParents(Collections.singletonList(parentId));   }   return driveInstance.files().create(fileMetadata)         .setFields("id")         .execute()         .getId(); }

Google Drive create all folders in path using Java client

In Google Drive you lot tin create a consummate nested path for a folder. Google Drive does non have direct support for the nested path, but it provides an alternative step by pace which you tin construct the required path. Treat each section of folder path as an contained folder and search sequentially which binder is present or which is not. The binder which is not institute, tin exist created there and search can exist performed at the side by side level.

For example, if we desire to create a path "/folder1/folder2/folder3" in Google Drive. Then we tin can split the path with a separator in an array of strings. Then from the first folder we will start checking in a recursive way, if the folder is not present and then nosotros create information technology and move forward.

public String getFolderId(String path) throws Exception {   Cord parentId = null;   Cord[] folderNames = path.split("/");    Drive driveInstance = googleDriveManager.getInstance();   for (String name : folderNames) {      parentId = findOrCreateFolder(parentId, proper noun, driveInstance);   }   return parentId; }

Google Drive upload file to a folder using Java client

Google Bulldoze provides a create method to upload files to Google Drive, which takes file InputStreamContent as parameter which represents content type and InputStream of target file. If a file needs to be uploaded in a specific folder then in FileMetaData, that folder'due south id tin be mentioned as parent.

In the following example, we are passing a multipart file instance from residual api and the desired path where the file should be uploaded. From the residual api we will upload the file and mention the folder path where this file should be uploaded.

// FileManager.coffee public String uploadFile(MultipartFile file, Cord filePath) {   try {      Cord folderId = getFolderId(filePath);      if (null != file) {         File fileMetadata = new File();         fileMetadata.setParents(Collections.singletonList(folderId));         fileMetadata.setName(file.getOriginalFilename());         File uploadFile = googleDriveManager.getInstance()               .files()               .create(fileMetadata, new InputStreamContent(                     file.getContentType(),                     new ByteArrayInputStream(file.getBytes()))               )               .setFields("id").execute();         return uploadFile.getId();      }   } grab (Exception e) {      log.error("Error: ", e);   }   return cipher; }  // MainController.java @PostMapping(value = "/upload",      consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},      produces = {MediaType.APPLICATION_JSON_VALUE} ) public ResponseEntity<Cord> uploadSingleFileExample4(@RequestBody MultipartFile file,@RequestParam(required = false) String path) {   log.info("Request contains, File: " + file.getOriginalFilename());   String fileId = fileManager.uploadFile(file, path);   if(fileId == null){      render ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();   }   return ResponseEntity.ok("Success, FileId: "+ fileId); }

Google Bulldoze download file using Java customer

Google Bulldoze allows you to download any file nowadays in Google Drive, the client library provides the methods named get and executeMediaAndDownloadTo. If you lot need to download multiple files, and then you lot accept to download files i by one  and then zero together these files. Google Drive client libraries don't support the Zipped file downloading feature. In Google bulldoze, every file has a unique file id, you lot demand to use this file id to download these files.

In the following example, nosotros are passing the file id from api and then using the Google Bulldoze service example nosotros can become the file and map it to the output stream in response.

// FileManager.coffee public void downloadFile(String id, OutputStream outputStream) throws IOException, GeneralSecurityException {   if (id != zippo) {      Cord fileId = id;      googleDriveManager.getInstance().files().go(fileId).executeMediaAndDownloadTo(outputStream);   } }  // MainController.java @GetMapping("/download/{id}") public void download(@PathVariable String id, HttpServletResponse response) throws IOException, GeneralSecurityException {   fileManager.downloadFile(id, response.getOutputStream()); }

Google Drive delete file using Java client

Google Drive stores all files with unique file id, Google Drive customer library can delete the files using these file ids. Google Drive client library has a delete method which accepts file id and on execution deletes the file from Google Drive.

In the following case, nosotros are creating a rest api which accepts file id and then deletes the file using that file id from Google Drive.

// FileManager.coffee public void deleteFile(String fileId) throws Exception {   googleDriveManager.getInstance().files().delete(fileId).execute(); }  // MainController.coffee @GetMapping("/delete/{id}") public void delete(@PathVariable String id) throws Exception {   fileManager.deleteFile(id); }

Source lawmaking

All the examples mentioned hither are nowadays in git repository You tin download the source code from github. In the example project the credentials file is bare for security reasons, y'all demand to create and add together your own credentials file at that place.

Determination

We hope this article will assist y'all understand the file operations in Google Drive Coffee client library with Spring boot. If yous want to larn more on uploading files, then you can check the article on Jump Boot multipart file upload examples.

roywitheyesse1999.blogspot.com

Source: https://technicalsand.com/file-operations-in-google-drive-api-with-spring-boot/

0 Response to "Uploading a File to Google Drive in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel