如何同时将多个文件上传到谷歌硬盘上的不同文件夹

时间:2016-01-25 02:19:26

标签: android file-upload google-drive-android-api

首先,这是我第一次在SO上发帖提问,所以如果我做错了,你可以随时给我建议。我的问题是帖子的标题,我成功上传多个文件到谷歌驱动器但我无法将它们上传到驱动器上的不同子文件夹。提前致谢

这是我的代码:

上传类来处理上传功能:

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 个答案:

答案 0 :(得分:0)

您正在基于1个driveId创建文件。您想要从不同的子文件夹创建/上传文件,每个子文件夹需要有不同的driveId对象。

另一种可能的解决方案是在创建/上传文件到不同的子文件夹时使用Drive REST API并调用Batch Requests(通过asynctask)。