google-app-enginegoogle-drive-apijava-iomultipartentity

Converting com.google.api.services.drive.model.File to java.io.File


So I want to create a java.io.File so that I can use it to generate a multipart-form POST request. I have the file in the form of a com.google.api.services.drive.model.File so I'm wondering, is there a way I can convert this Google File to a Java File? This is a web-app that uses the Google App Engine SDK, which prohibits every approach I've tried to make this work


Solution

  • No, you it doesn't seem like you can convert from com.google.api.services.drive.model.File to java.io.File. But it should still be possible to generate a multipart-form POST request using your data in Drive.

    So the com.google.api.services.drive.model.File class is used for storing metadata about the file. It's not storing the file contents.

    If you want to read the contents of your file into memory, this code snippet from the Drive documentation shows how to do it. Once the file is in memory, you can do whatever you want with it.

     /**
     * Download the content of the given file.
     *
     * @param service Drive service to use for downloading.
     * @param file File metadata object whose content to download.
     * @return String representation of file content.  String is returned here
     *         because this app is setup for text/plain files.
     * @throws IOException Thrown if the request fails for whatever reason.
     */
    private String downloadFileContent(Drive service, File file)
        throws IOException {
      GenericUrl url = new GenericUrl(file.getDownloadUrl());
      HttpResponse response = service.getRequestFactory().buildGetRequest(url)
          .execute();
      try {
        return new Scanner(response.getContent()).useDelimiter("\\A").next();
      } catch (java.util.NoSuchElementException e) {
        return "";
      }
    }
    

    https://developers.google.com/drive/examples/java

    This post might be helpful for making your multi-part POST request from Google AppEngine.