【问题标题】:Upload file to existing Google Drive Folder - Android将文件上传到现有的 Google Drive 文件夹 - Android
【发布时间】:2024-09-25 20:35:02
【问题描述】:

我想将文件上传到现有的 Google Drive 文件夹。

我正在使用这个how to upload an image from my android app to a specific folder on google drive 来获取文件夹名称,但不确定如何实现它(smokybob 的回答)

 //Search by name and type folder
 String qStr = "mimeType = 'application/vnd.google-apps.folder' and title = 'myFolder'";

 //Get the list of Folders
 FileList fList=service.files().list().setQ(qStr).execute();

 //Check that the result is one folder
 File folder;

 if (fList.getItems().lenght==0){
 folder=fList.getItems()[0]; 
 }

 //Create the insert request is as in the sample

 File file = service.files().insert(body, mediaContent);

 //set the parent

 file.setParents(Arrays.asList(newParentReference().setId(folder.getFolderId())));

 //execute the request 

 file.execute();

我得到无法解决 FileList、正文、媒体内容的符号错误。 我无法解析 .files、getitems()、setparents、newparentsreference 和执行的方法。

类:GetFile.java https://github.com/googledrive/android-demos/blob/master/src/com/google/android/gms/drive/sample/demo/CreateFileActivity.java

     public class GetFile extends UploadDrive {

private static final String TAG = "CreateFileActivity";

@Override
public void onConnected(Bundle connectionHint) {
    super.onConnected(connectionHint);
    // create new contents resource
    Drive.DriveApi.newDriveContents(getGoogleApiClient())
            .setResultCallback(driveContentsCallback);
}

final private ResultCallback<DriveContentsResult> driveContentsCallback = new
        ResultCallback<DriveContentsResult>() {
            @Override
            public void onResult(DriveContentsResult result) {
                if (!result.getStatus().isSuccess()) {
                    showMessage("Error while trying to create new file contents");
                    return;
                }
                final DriveContents driveContents = result.getDriveContents();

                // Perform I/O off the UI thread.
                new Thread() {
                    @Override
                    public void run() {
                        // write content to DriveContents
                        OutputStream outputStream = driveContents.getOutputStream();
                        Writer writer = new OutputStreamWriter(outputStream);
                        try {
                            writer.write(MainActivity.driveText); //what is the problem?
                            writer.close();
                        } catch (IOException e) {
                            Log.e(TAG, e.getMessage());
                        }

                        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                .setTitle("New file")
                                .setMimeType("text/plain")
                                .setStarred(true).build();

                        // create a file on root folder
                        Drive.DriveApi.getRootFolder(getGoogleApiClient())
                                .createFile(getGoogleApiClient(), changeSet, driveContents)
                                .setResultCallback(fileCallback);
                    }
                }.start();
            }
        };

final private ResultCallback<DriveFileResult> fileCallback = new
        ResultCallback<DriveFileResult>() {
            @Override
            public void onResult(DriveFileResult result) {
                if (!result.getStatus().isSuccess()) {
                    showMessage("Error while trying to create the file");
                    return;
                }
                showMessage("Created a file with content: " + result.getDriveFile().getDriveId());
            }
        };
}

【问题讨论】:

  • 您的“driveText”字符串在 MainActivity 中是公开的还是静态的?如果没有,请尝试。
  • @Sw4Tish 我更新了它,现在我得到一个空值。
  • 如果您的字符串不会更改,请尝试以下操作:public static final String driveText = "YOUR_STRING" 并像这样调用它:MainActivity.driveText
  • 谢谢,我解决了这个问题。现在我的问题是:如何选择用户事先创建的文件夹。问题已更新。

标签: java android google-drive-api


【解决方案1】:

在 GDAA 下创建文件夹时,它会生成 DriveId。

/**************************************************************************
   * create file/folder in GOODrive
   * @param prnId  parent's ID, (null or "root") for root
   * @param titl  file name
   * @param mime  file mime type
   * @param file  file (with content) to create (optional, if null, create folder)
   * @return      file id  / null on fail
   */
  static String create(String prnId, String titl, String mime, java.io.File file) {
    DriveId dId = null;
    if (mGAC != null && mGAC.isConnected() && titl != null) try {
      DriveFolder pFldr = (prnId == null || prnId.equalsIgnoreCase("root")) ?
      Drive.DriveApi.getRootFolder(mGAC):
      Drive.DriveApi.getFolder(mGAC, DriveId.decodeFromString(prnId));
      if (pFldr == null) return null; //----------------->>>

      MetadataChangeSet meta;
      if (file != null) {  // create file
        if (mime != null) {   // file must have mime
          DriveContentsResult r1 = Drive.DriveApi.newDriveContents(mGAC).await();
          if (r1 == null || !r1.getStatus().isSuccess()) return null; //-------->>>

          meta = new MetadataChangeSet.Builder().setTitle(titl).setMimeType(mime).build();
          DriveFileResult r2 = pFldr.createFile(mGAC, meta, r1.getDriveContents()).await();
          DriveFile dFil = r2 != null && r2.getStatus().isSuccess() ? r2.getDriveFile() : null;
          if (dFil == null) return null; //---------->>>

          r1 = dFil.open(mGAC, DriveFile.MODE_WRITE_ONLY, null).await();
          if ((r1 != null) && (r1.getStatus().isSuccess())) try {
            Status stts = file2Cont(r1.getDriveContents(), file).commit(mGAC, meta).await();
            if ((stts != null) && stts.isSuccess()) {
              MetadataResult r3 = dFil.getMetadata(mGAC).await();
              if (r3 != null && r3.getStatus().isSuccess()) {
                dId = r3.getMetadata().getDriveId();
              }
            }
          } catch (Exception e) {
            UT.le(e);
          }
        }

      } else {
        meta = new MetadataChangeSet.Builder().setTitle(titl).setMimeType(UT.MIME_FLDR).build();
        DriveFolderResult r1 = pFldr.createFolder(mGAC, meta).await();
        DriveFolder dFld = (r1 != null) && r1.getStatus().isSuccess() ? r1.getDriveFolder() : null;
        if (dFld != null) {
          MetadataResult r2 = dFld.getMetadata(mGAC).await();
          if ((r2 != null) && r2.getStatus().isSuccess()) {
            dId = r2.getMetadata().getDriveId();
          }
        }
      }
    } catch (Exception e) { UT.le(e); }
    return dId == null ? null : dId.encodeToString();
  } 

(必须在非 UI 线程上运行)
此 ID 在后续调用中用作“父 ID”。如果您对未解决的方法有疑问,请参阅此GitHub 项目。顺便说一句(正如我之前提到的),它可以完成您想要完成的所有事情(创建文件夹,创建文本文件,读回内容,删除文件/文件夹,......)

祝你好运

【讨论】:

  • 我不明白您创建的 DriveFolder 功能是如何工作的。
  • 我不想使用你的项目,但是按照你提供的方法,我如何才能将文件夹部分整合到我所拥有的?