How do I upload file to google drive from android

前端 未结 4 1155
刺人心
刺人心 2021-01-03 07:20

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

相关标签:
4条回答
  • 2021-01-03 07:36

    Hi guys i get 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.

    0 讨论(0)
  • 2021-01-03 07:38

    Upload File to Google Drive

    Drive.Files.Insert insert;
    try {
        final java.io.File uploadFile = new java.io.File(filePath);
        File fileMetadata = new File();
        ParentReference newParent = new ParentReference();
        newParent.setId(upload_folder_ID);
        fileMetadata.setParents(
                Arrays.asList(newParent));
        fileMetadata.setTitle(fileName);
        InputStreamContent mediaContent = new InputStreamContent(MIMEType, new BufferedInputStream(
                    new FileInputStream(uploadFile) {
                        @Override
                        public int read(byte[] buffer,
                                int byteOffset, int byteCount)
                                throws IOException {
                            // TODO Auto-generated method stub
                            Log.i("chauster","progress = "+byteCount);
                            return super.read(buffer, byteOffset, byteCount);
                        }
                    }));
                mediaContent.setLength(uploadFile.length());
        insert = service.files().insert(fileMetadata, mediaContent);
        MediaHttpUploader uploader = insert.getMediaHttpUploader();
        FileUploadProgressListener listener = new FileUploadProgressListener();
        uploader.setProgressListener(listener);
        uploader.setDirectUploadEnabled(true);
        insert.execute();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    public class FileUploadProgressListener implements MediaHttpUploaderProgressListener {
    
        @SuppressWarnings("incomplete-switch")
        @Override
        public void progressChanged(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

    0 讨论(0)
  • 2021-01-03 07:38

    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. */
      private static 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();
        // authorize
        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
      } 
    

    The library runs on Google App Engine

    Media Upload

    class CustomProgressListener implements MediaHttpUploaderProgressListener {
      public void progressChanged(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!");
        }
      }
    }
    
    File mediaFile = new File("/tmp/driveFile.jpg");
    InputStreamContent mediaContent =
        new InputStreamContent("image/jpeg",
            new BufferedInputStream(new FileInputStream(mediaFile)));
    mediaContent.setLength(mediaFile.length());
    
    Drive.Files.Insert request = drive.files().insert(fileMetadata, mediaContent);
    request.getMediaHttpUploader().setProgressListener(new CustomProgressListener());
    request.execute();
    

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

    File mediaFile = new File("/tmp/Test.jpg");
    InputStreamContent mediaContent =
        new InputStreamContent("image/jpeg",
            new BufferedInputStream(new FileInputStream(mediaFile)));
    mediaContent.setLength(mediaFile.length());
    
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, transport, httpRequestInitializer);
    uploader.setProgressListener(new CustomProgressListener());
    HttpResponse response = uploader.upload(requestUrl);
    if (!response.isSuccessStatusCode()) {
      throw GoogleJsonResponseException(jsonFactory, response);
    }
    
    0 讨论(0)
  • 2021-01-03 07:39

    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.

    0 讨论(0)
提交回复
热议问题