简体   繁体   中英

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 find any method which upload / download files.

I try Google Client libraries but there are some method are not resolved.

such as :

service.files().insert(body, mediaContent).execute();
errors: The method execute() is undefined for the type Drive.Files.Insert

I can upload image through below code but this is Google Drive file up loader. I can only upload one only one file at a time.

mFile = new java.io.File(fileList.get(i));
                Log.i(TAG, "Creating new contents.");
                Drive.DriveApi.newContents(mGoogleApiClient).addResultCallback(
                        new OnNewContentsCallback() {

                            @Override
                            public void onNewContents(ContentsResult result) {

                                if (!result.getStatus().isSuccess()) {
                                    Log.i(TAG, "Failed to create new contents.");
                                    return;
                                }

                                Log.i(TAG, "New contents created.");

                                OutputStream outputStream = result
                                        .getContents().getOutputStream();

                                byte[] byteStream = new byte[(int) mFile
                                        .length()];
                                try {
                                    outputStream.write(byteStream);
                                } catch (IOException e1) {
                                    Log.i(TAG, "Unable to write file contents.");
                                }

                                MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                                        .setMimeType("image/jpeg")
                                        .setMimeType("text/html")
                                        .setTitle("Android Photo.png").build();
                                // Create an intent for the file chooser, and
                                // start it.
                                IntentSender intentSender = Drive.DriveApi
                                        .newCreateFileActivityBuilder()
                                        .setInitialMetadata(metadataChangeSet)
                                        .setInitialContents(
                                                result.getContents())
                                        .build(mGoogleApiClient);
                                try {
                                    mActivity.startIntentSenderForResult(
                                            intentSender, REQUEST_CODE_CREATOR,
                                            null, 0, 0, 0);
                                    publishProgress(1);
                                } catch (SendIntentException e) {
                                    Log.i(TAG, "Failed to launch file chooser.");
                                    publishProgress(0);
                                }
                            }
                        });

But still fighting for downloading a file.

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.

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

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);
}

经过几天寻找一个好例子,我发现GitHub上Google I / O应用程序具有很好的实用程序方法,可以从Drive创建,更新和读取文件。

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.

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