2015-01-31 9 views
10

내 내부 저장소에있는 이미지를 여러 개 보내고 싶습니다. 폴더를 선택하면 해당 폴더를 Google 드라이브에 업로드하고 싶습니다. 내가 https://developers.google.com/drive/android/create-file 안드로이드 이 구글 드라이브 API를 시도하고 난 아래의 코드를 사용하고 있지만, 구동 이미지 또는 Gmail을 보낼 수있는 방법이 코드가폴더에있는 여러 개의 이미지를 Android 드라이브의 Google 드라이브에 프로그래밍 방식으로 보내는 방법은 무엇입니까?

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 
     } 
    } 
} 

입니다 getGoogleApiClient

에서 일부 오류가 표시 ?

+0

"자세한 오류 표시": 세부 사항 부탁드립니다! – Henry

+0

여기에 오류가 표시됩니다. build (getGoogleApiClient()); getGoogleApiClient를 사용할 수 없다는 것을 보여 주며 빌드에서 전달할 GoogleApiClient 용 개체를 만들 수 없습니다. – Hanuman

답변

3

정확한 코드를 제공 할 수는 없지만 the code I use for testing Google 드라이브 Android API (GDAA)를 수정하려고 할 수 있습니다. 폴더를 만들고 Google 드라이브에 파일을 업로드합니다. REST 또는 GDAA 맛을 선택하는 것은 당신에게 달렸습니다. 각각 고유 한 이점이 있습니다.

이것은 질문의 절반 만 다루고 있습니다. Android 기기에서 파일을 선택하고 열거하는 것은 다른 곳에서 다루어야합니다.

UPDATE : (아래 프랭크의 코멘트 당)

나는 당신에게 처음부터 전체 솔루션을 제공하지만, 이제 질문의 포인트를 처리 할 것입니다 위에서 언급 한 예 내가 해독 할 수 있습니다 :

장애물 '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에서 파일을 열거/(단순에 대한 JPEG 여기에 사용) 각 파일의 이름, 내용과 MIME 타입을 설정 : 여기에 코드입니다. 구글의 루트 폴더에 각 파일이 여기에 코드가 GDAA wrapper here에서 직접 촬영 말할

// 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; 
} 

바늘 ( 방법은 오프 UI 스레드를 실행해야합니다) (작성 )
드라이브
3/업로드 (처음에 언급 했으므로) 참조를 해결해야 할 경우 코드를 찾아야합니다.

행운을 빌어 요