android - 如何以编程方式将文件夹中存在的多个图像发送到 android 中的谷歌驱动器?

标签 android image google-drive-android-api file-manager

我想发送多张存在于我的内部存储中的图像,当我选择该文件夹时,我想将该文件夹上传到谷歌驱动器中。我已经尝试过这个适用于 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
        }
    }
}

有什么方法可以将图片发送到驱动器或 gmail 吗?

最佳答案

我无法为您提供满足您需要的确切代码,但您可以尝试修改 the code I use for testing谷歌云端硬盘 Android API (GDAA)。它创建文件夹并将文件上传到 Google 云端硬盘。选择 REST 还是 GDAA 风格取决于您,每种风格都有其特定的优势。

不过,这只涵盖了您问题的一半。在您的 Android 设备上选择和枚举文件应该在别处介绍。

更新:(根据下面弗兰克的评论)

我上面提到的例子会给你一个从头开始的完整解决方案,但让我们来解决你的问题我可以破译的要点:

障碍“一些错误”是一种返回在您的代码序列之前初始化的 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/上传每个文件到谷歌驱动器的根文件夹
(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 (在开头提到),所以如果您需要解决任何引用,您必须在那里查找代码。

祝你好运

关于android - 如何以编程方式将文件夹中存在的多个图像发送到 android 中的谷歌驱动器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28250336/

相关文章:

c# - Android 应用程序调试几秒钟然后停止

java - 如何制作 LibGDX + Android Studio jar 文件?

html - 图像悬停使用 html 或 css

Android 以指定帐户的 Intent 打开谷歌驱动器

Android:如何根据所选项目的值更改操作栏标题

android - 在 Canvas 上绘制部分图像

java - 如何在 .jar 中包含和访问图像

java - 无法从 2 个不同的设备访问 Google 云端硬盘

android - GoogleApiClient 连接失败,ConnectionResult 状态码为 SIGN_IN_REQUIRED

java - 使用 Android 将数据插入 Windows Azure 表?