How to upload multi files to different folders on google drive at the same time

蹲街弑〆低调 提交于 2019-12-12 05:25:19

问题


firstly, it's my first time i post a question on SO so you can feel free to give me advices if i make something wrong. My question is post's title, i am success to upload multi file to google drive but i can not upload them into different sub folders on drive. Thanks in advance

Here is my code:

Upload class to handle upload function:

public class UploadFileActivity  /*implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener*/ {
private static final String TAG = "upload_file";
private static final int REQUEST_CODE = 101;
public File textFile;
public GoogleApiClient googleApiClient;
public static String drive_id;
public static DriveId driveID;
public Context mContext;
public String folder_id;
public  String foler_backup_id;
public String foler_backup_name;
SharedPreferences sharedPreferences;


public void testDrive(){

    Drive.DriveApi.fetchDriveId(googleApiClient,folder_id).setResultCallback(idCallback);
}

final private ResultCallback<DriveApi.DriveIdResult> idCallback = new
        ResultCallback<DriveApi.DriveIdResult>() {
            @Override
            public void onResult(DriveApi.DriveIdResult driveIdResult) {
                if(!driveIdResult.getStatus().isSuccess()){
                    Toast.makeText(mContext,"Cannot find DriveId. Are you authorized to view this file?",Toast.LENGTH_LONG).show();
                    return;
                }
                Log.d("check_up", "1");
                driveID = driveIdResult.getDriveId();


                final DriveFolder folder = driveID.asDriveFolder();
                folder.listChildren(googleApiClient).setResultCallback(metadataResult);

               /* Drive.DriveApi.newDriveContents(googleApiClient)

                        .setResultCallback(driveContentsCallback);*/
            }
        };

/*callback on getting the drive contents, contained in result*/
final private ResultCallback<DriveContentsResult> driveContentsCallback = new
        ResultCallback<DriveContentsResult>() {
            @Override
            public void onResult(DriveContentsResult result) {
                if (!result.getStatus().isSuccess()) {
                    Log.i(TAG, "Error creating new file contents");
                    return;
                }
                final DriveFolder folder = driveID.asDriveFolder();

                Log.d("check_folder",folder.toString());
                final DriveContents driveContents = result.getDriveContents();
                new Thread() {
                    @Override
                    public void run() {
                        OutputStream outputStream = driveContents.getOutputStream();
                        addTextfileToOutputStream(outputStream);
                        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                .setTitle(textFile.getName())
                                .setMimeType("text/plain")
                                .setDescription("This is a text file uploaded from device")
                                .setStarred(true).build();

                        //root folder
                        /*Drive.DriveApi.getRootFolder(googleApiClient)
                                .createFile(googleApiClient, changeSet, driveContents)
                                .setResultCallback(fileCallback);*/

                        //file in folder
                        folder.createFile(googleApiClient, changeSet, driveContents)
                                .setResultCallback(fileCallback);

                        //file in app folder
                        /*Drive.DriveApi.getAppFolder(googleApiClient)
                                .createFile(googleApiClient, changeSet, driveContents)
                                .setResultCallback(fileCallback);*/
                    }

                }.start();
            }
        };

/*get input stream from text file, read it and put into the output stream*/
private void addTextfileToOutputStream(OutputStream outputStream) {
    Log.i(TAG, "adding text file to outputstream...");
    byte[] buffer = new byte[1024];
    int bytesRead;
    try {
        BufferedInputStream inputStream = new BufferedInputStream(
                new FileInputStream(textFile));
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        Log.i(TAG, "problem converting input stream to output stream: " + e);
        e.printStackTrace();
    }
}

/*callback after creating the file, can get file info out of the result*/
final private ResultCallback<DriveFileResult> fileCallback = new
        ResultCallback<DriveFileResult>() {
            @Override
            public void onResult(DriveFileResult result) {
                if (!result.getStatus().isSuccess()) {
                    Log.i(TAG, "Error creating the file");
                    Toast.makeText(mContext,
                            "Error adding file to Drive", Toast.LENGTH_SHORT).show();
                    return;
                }

                Log.i(TAG, "File added to Drive");
                Log.i(TAG, "Created a file with content: "
                        + result.getDriveFile().getDriveId());
                /*Toast.makeText(mContext,
                        "Files successfully added to Drive", Toast.LENGTH_SHORT).show();*/
                listener.onReceive();
                final PendingResult<DriveResource.MetadataResult> metadata
                        = result.getDriveFile().getMetadata(googleApiClient);
                metadata.setResultCallback(new
                                                   ResultCallback<DriveResource.MetadataResult>() {
                                                       @Override
                                                       public void onResult(DriveResource.MetadataResult metadataResult) {

                                                           Metadata data = metadataResult.getMetadata();
                                                           Log.i(TAG, "Title: " + data.getTitle());
                                                           drive_id = data.getDriveId().encodeToString();
                                                           Log.i(TAG, "DrivId: " + drive_id);
                                                           driveID = data.getDriveId();
                                                           Log.i(TAG, "Description: " + data.getDescription().toString());
                                                           Log.i(TAG, "MimeType: " + data.getMimeType());
                                                           Log.i(TAG, "File size: " + String.valueOf(data.getFileSize()));
                                                       }
                                                   });
            }
        };

final private ResultCallback<DriveApi.MetadataBufferResult> metadataResult = new
        ResultCallback<DriveApi.MetadataBufferResult>() {
            @Override
            public void onResult(DriveApi.MetadataBufferResult result) {
                if (!result.getStatus().isSuccess()) {
                    //showMessage("Problem while retrieving files");
                    Log.d("check_title", "Problem while retrieving files");
                    return;
                }
                Log.d("check_folder_backup",foler_backup_name);
                for(int i = 0;i<result.getMetadataBuffer().getCount();i++){
                    Metadata metadata = result.getMetadataBuffer().get(i);
                    if(metadata.isFolder()){
                        if(metadata.getTitle().equals(foler_backup_name)){
                            foler_backup_id = metadata.getDriveId().getResourceId();
                            break;
                        }
                    }
                    Log.d("check_title",metadata.getTitle() + " " + metadata.isFolder());
                }
                //Log.d("check_folder_backup_id",foler_backup_id);
                if(foler_backup_id==null){
                    Drive.DriveApi.fetchDriveId(googleApiClient,folder_id).setResultCallback(preCreateFolder);
                }else {
                    Drive.DriveApi.fetchDriveId(googleApiClient,foler_backup_id).setResultCallback(preCreateFile);
                }

            }
        };

final private ResultCallback<DriveApi.DriveIdResult> preCreateFile = new
        ResultCallback<DriveApi.DriveIdResult>() {
            @Override
            public void onResult(DriveApi.DriveIdResult driveIdResult) {
                if(!driveIdResult.getStatus().isSuccess()){
                    Toast.makeText(mContext,"Cannot find DriveId. Are you authorized to view this file?",Toast.LENGTH_LONG).show();
                    return;
                }
                Log.d("check_up", "10");
                 driveID = driveIdResult.getDriveId();

                Log.d("check_drive_id",driveID.toString());

                //folder.listChildren(googleApiClient).setResultCallback(metadataResult);

                Drive.DriveApi.newDriveContents(googleApiClient)

                        .setResultCallback(driveContentsCallback);
            }
        };

final ResultCallback<DriveApi.DriveIdResult>preCreateFolder = new ResultCallback<DriveApi.DriveIdResult>() {
    @Override
    public void onResult(DriveApi.DriveIdResult driveIdResult) {
        if(!driveIdResult.getStatus().isSuccess()){
            Log.d("Check_error","Cannot find DriveId. Are you authorized to view this file?");
            return;
        }
        Log.d("Check_error","4");
        DriveId driveId = driveIdResult.getDriveId();
        DriveFolder folder = driveId.asDriveFolder();
        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                .setTitle(foler_backup_name).build();
        folder.createFolder(googleApiClient,changeSet)
                .setResultCallback(createFolderCallBack);
    }
};

final ResultCallback<DriveFolder.DriveFolderResult> createFolderCallBack = new ResultCallback<DriveFolder.DriveFolderResult>() {
    @Override
    public void onResult(DriveFolder.DriveFolderResult driveFolderResult) {
        if(!driveFolderResult.getStatus().isSuccess()){
            return;
        }
        Log.d("thong_bao","Folder successfully created");
        Drive.DriveApi.fetchDriveId(googleApiClient,foler_backup_id).setResultCallback(preCreateFile);
    }
};


public interface OnCatch{
    public void onReceive();
}

private OnCatch listener;

public void setCatch(OnCatch listener){
    this.listener = listener;
}

}


回答1:


You're creating files based on 1 driveId. You want to create/upload files from different subfolders, you need to have different driveId objects per subfolder.

Another possible solution would be for you to use the Drive REST APIs and call Batch Requests (thru asynctask) when creating/uploading files in to different subfolders.



来源:https://stackoverflow.com/questions/34984163/how-to-upload-multi-files-to-different-folders-on-google-drive-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!