How do I upload file to google drive from android

前端 未结 4 1134
刺人心
刺人心 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: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

提交回复
热议问题