如何在Android程序中以编程方式将文件夹中存在的多个图像发送到Google Drive?

10
我想发送保存在我的内部存储中的多个图像,并且当我选择该文件夹时,我想将该文件夹上传到Google Drive。我已经尝试了这个适用于Android的Google Drive API:https://developers.google.com/drive/android/create-file。我已经使用了下面的代码,但它显示了getGoogleApiClient的一些错误。
代码:
ResultCallback<DriveContentsResult> contentsCallback = new
        ResultCallback<DriveContentsResult>() {
    @Override
    public void onResult(DriveContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            // Handle error
            return;
        }

        MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                .setMimeType("text/html").build();
        IntentSender intentSender = Drive.DriveApi
                .newCreateFileActivityBuilder()
                .setInitialMetadata(metadataChangeSet)
                .setInitialDriveContents(result.getDriveContents())
                .build(getGoogleApiClient());
        try {
            startIntentSenderForResult(intentSender, 1, null, 0, 0, 0);
        } catch (SendIntentException e) {
            // Handle the exception
        }
    }
}

是否有方法将图片发送到Google云端硬盘或Gmail?


显示了一些错误:请提供详细信息! - Henry
这里显示错误.build(getGoogleApiClient()); 它显示getGoogleApiClient不可用,我无法创建GoogleApiClient对象以传递到build。 - Hanuman
1个回答

3
我无法给你提供确切的代码来实现你需要的功能,但你可以尝试修改我用于测试Google Drive Android API(GDAA)的代码。它可以创建文件夹并将文件上传到Google Drive。你可以选择使用REST或GDAA版本,每个版本都有其特定的优势。
虽然如此,这只涵盖了你问题的一半。在Android设备上选择和枚举文件应该在其他地方解决。
更新:(根据下面Frank的评论)
我之前提到的示例会为你提供一个从头开始的完整解决方案,但让我们来解决你问题中我能理解的部分:
障碍“some error”是一个在代码序列之前初始化的返回GoogleApiClient对象的方法。它看起来像:
  GoogleApiClient mGAC = new GoogleApiClient.Builder(appContext)
  .addApi(Drive.API).addScope(Drive.SCOPE_FILE)
  .addConnectionCallbacks(callerContext)
  .addOnConnectionFailedListener(callerContext)
  .build();

如果你已经清楚了这一点,那么我们假设你的文件夹由一个java.io.File对象表示。以下是代码:
1/ 枚举本地文件夹中的文件
2/ 设置每个文件的名称、内容和MIME类型(这里为了简单起见使用jpeg)。
3/ 将每个文件上传到Google Drive的根文件夹中
(create()方法必须在非UI线程中运行)
// enumerating files in a folder, uploading to Google Drive
java.io.File folder = ...;
for (java.io.File file : folder.listFiles()) {
  create("root", file.getName(), "image/jpeg", file2Bytes(file))
}

/******************************************************
 * 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 buf   file contents  (optional, if null, create folder)
 * @return      file id  / null on fail
 */
static String create(String prnId, String titl, String mime, byte[] buf) {
  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 (buf != null) {  // create file
        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 = bytes2Cont(r1.getDriveContents(), buf).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) { /* error handling*/ }

    } else {
      meta = new MetadataChangeSet.Builder().setTitle(titl).setMimeType("application/vnd.google-apps.folder").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) { /* error handling*/ }
  return dId == null ? null : dId.encodeToString();
}
//-----------------------------
static byte[] file2Bytes(File file) {
  if (file != null) try {
    return is2Bytes(new FileInputStream(file));
  } catch (Exception e) {}
  return null;
}
//----------------------------
static byte[] is2Bytes(InputStream is) {
  byte[] buf = null;
  BufferedInputStream bufIS = null;
  if (is != null) try {
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
    bufIS = new BufferedInputStream(is);
    buf = new byte[2048];
    int cnt;
    while ((cnt = bufIS.read(buf)) >= 0) {
      byteBuffer.write(buf, 0, cnt);
    }
    buf = byteBuffer.size() > 0 ? byteBuffer.toByteArray() : null;
  } catch (Exception e) {}
  finally {
    try {
      if (bufIS != null) bufIS.close();
    } catch (Exception e) {}
  }
  return buf;
}
//--------------------------
private static DriveContents bytes2Cont(DriveContents driveContents, byte[] buf) {
   OutputStream os = driveContents.getOutputStream();
   try { os.write(buf);
   } catch (IOException e)  {/*error handling*/}
    finally {
     try { os.close();
     } catch (Exception e) {/*error handling*/}
   }
   return driveContents;
 }

不用说,这里的代码直接取自GDAA wrapper here(在开头提到),所以如果您需要解决任何引用问题,您必须查找那里的代码。

祝好运


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接