Skip to content Skip to sidebar Skip to footer

How Do I Upload File To Google Drive From Android

I have spend more then one day but not getting any working solution which provide me uploading / downloading files to Google Drive. I have tried Google Play Service but i didn't f

Solution 1:

I got the solution. We should never use Android API for complete Drive access. We should work on pure java code as Google also said that to access Drive for broad access use java libraries.

I remove all the code related to Google play services. I am now using completely using java and easily upload, delete, edit, download all whatever I want.

One more thing Google doc doesn't provide a detail description about Google Drive in respective to android api while when work on java libraries you can get already created methods and more.

I am not giving any code but saying that for me or for others who interested in Drive complete access use Java based codes.

Solution 2:

Upload File to Google Drive

Drive.Files.Insert insert;
try {
    final java.io.FileuploadFile=newjava.io.File(filePath);
    FilefileMetadata=newFile();
    ParentReferencenewParent=newParentReference();
    newParent.setId(upload_folder_ID);
    fileMetadata.setParents(
            Arrays.asList(newParent));
    fileMetadata.setTitle(fileName);
    InputStreamContentmediaContent=newInputStreamContent(MIMEType, newBufferedInputStream(
                newFileInputStream(uploadFile) {
                    @Overridepublicintread(byte[] buffer,
                            int byteOffset, int byteCount)throws IOException {
                        // TODO Auto-generated method stub
                        Log.i("chauster","progress = "+byteCount);
                        returnsuper.read(buffer, byteOffset, byteCount);
                    }
                }));
            mediaContent.setLength(uploadFile.length());
    insert = service.files().insert(fileMetadata, mediaContent);
    MediaHttpUploaderuploader= insert.getMediaHttpUploader();
    FileUploadProgressListenerlistener=newFileUploadProgressListener();
    uploader.setProgressListener(listener);
    uploader.setDirectUploadEnabled(true);
    insert.execute();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

publicclassFileUploadProgressListenerimplementsMediaHttpUploaderProgressListener {

    @SuppressWarnings("incomplete-switch")@OverridepublicvoidprogressChanged(MediaHttpUploader uploader)throws IOException {
        switch (uploader.getUploadState()) {
            case INITIATION_STARTED:
                break;
            case INITIATION_COMPLETE:
                break;
            case MEDIA_IN_PROGRESS:
                break;
            case MEDIA_COMPLETE:
                break;
        }
    }
}

and Download file from google drive look this

Solution 3:

Google SDK is now android friendly. There is a full-access scope which gives you access to listing and reading all the drive files and which can be used in Android apps easily since our newer client library is Android-friendly! I also recommend watching this talk from Google IO which is explains how to integrate mobile apps with Drive

The library makes authentication easier

/** Authorizes the installed application to access user's protected data. */privatestatic Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(CalendarSample.class.getResourceAsStream("/client_secrets.json")));
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, JSON_FACTORY, clientSecrets,
        Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
        .build();
    // authorizereturnnew AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  } 

The library runs on Google App Engine

Media Upload

classCustomProgressListenerimplementsMediaHttpUploaderProgressListener {
  publicvoidprogressChanged(MediaHttpUploader uploader)throws IOException {
    switch (uploader.getUploadState()) {
      case INITIATION_STARTED:
        System.out.println("Initiation has started!");
        break;
      case INITIATION_COMPLETE:
        System.out.println("Initiation is complete!");
        break;
      case MEDIA_IN_PROGRESS:
        System.out.println(uploader.getProgress());
        break;
      case MEDIA_COMPLETE:
        System.out.println("Upload is complete!");
    }
  }
}

FilemediaFile=newFile("/tmp/driveFile.jpg");
InputStreamContentmediaContent=newInputStreamContent("image/jpeg",
        newBufferedInputStream(newFileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());

Drive.Files.Insertrequest= drive.files().insert(fileMetadata, mediaContent);
request.getMediaHttpUploader().setProgressListener(newCustomProgressListener());
request.execute();

You can also use the resumable media upload feature without the service-specific generated libraries. Here is an example:

FilemediaFile=newFile("/tmp/Test.jpg");
InputStreamContentmediaContent=newInputStreamContent("image/jpeg",
        newBufferedInputStream(newFileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());

MediaHttpUploaderuploader=newMediaHttpUploader(mediaContent, transport, httpRequestInitializer);
uploader.setProgressListener(newCustomProgressListener());
HttpResponseresponse= uploader.upload(requestUrl);
if (!response.isSuccessStatusCode()) {
  throw GoogleJsonResponseException(jsonFactory, response);
}

Solution 4:

I also tried this, I was searching for tutorials to upload some user data to their own account. But I did not found anything. Google suggests google firebase storage instead of google drive. If you think, how WhatsApp uses google drive to upload data. Then my answer is that google provides special service to WhatsApp. So use firebase storage, it is easy and very cheap and also updated. Use documentation to use them very properly. The docs are really awesome.

Post a Comment for "How Do I Upload File To Google Drive From Android"