2012-03-22 11 views
19

Jak mogę przesłać plik (plik graficzny, audio i wideo) z Androidem za pomocą interfejsu API Dropbox do Dropbox? Śledziłem samouczek na stronie Dropbox SDK Android i mogłem pobrać próbkę. Ale teraz zamiast String chcę przesłać rzeczywisty obiekt File i walczę.Korzystanie z interfejsu API Dropbox do przesyłania plików za pomocą Androida

Przykładowy kod działa bez żadnych problemów i wygląda następująco:

String fileContents = "Hello World!"; 
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContents.getBytes()); 
try { 
    Entry newEntry = mDBApi.putFile("/testing_123456.txt", inputStream, fileContents.length(), null, null); 
} catch (DropboxUnlinkedException e) { 
    Log.e("DbExampleLog", "User has unlinked."); 
} catch (DropboxException e) { 
    Log.e("DbExampleLog", "Something went wrong while uploading."); 
} 

Ale gdy próbuję ją zmienić i przesłać rzeczywiste plik z tym kodem:

File tmpFile = new File(fullPath, "IMG_2012-03-12_10-22-09_thumb.jpg"); 

// convert File to byte[] 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
ObjectOutputStream oos = new ObjectOutputStream(bos); 
oos.writeObject(tmpFile); 
bos.close(); 
oos.close(); 
byte[] bytes = bos.toByteArray(); 

ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); 
try { 
    Entry newEntry = mDBApi.putFile("/IMG_2012-03-12_10-22-09_thumb.jpg", inputStream, tmpFile.length(), null, null); 
} catch (DropboxUnlinkedException e) { 
    Log.e("DbExampleLog", "User has unlinked."); 
} catch (DropboxException e) { 
    Log.e("DbExampleLog", "Something went wrong while uploading."); 
} 

nie mam sukcesów uzyskanie błędu DropboxException. Myślę, że coś, co próbuję przekonwertować obiekt File do strumienia bajtów, musi być złe, ale to tylko założenie.

Inny niż przykład String nie ma nic więcej udokumentowanego na stronie Dropbox dla Androida.

Dzięki za pomoc.

Odpowiedz

23

znalazłem rozwiązanie - jeśli ktoś jest zainteresowany Oto kod działa:

private DropboxAPI<AndroidAuthSession> mDBApi;//global variable 

File tmpFile = new File(fullPath, "IMG_2012-03-12_10-22-09_thumb.jpg"); 

FileInputStream fis = new FileInputStream(tmpFile); 

      try { 
       DropboxAPI.Entry newEntry = mDBApi.putFileOverwrite("IMG_2012-03-12_10-22-09_thumb.jpg", fis, tmpFile.length(), null); 
      } catch (DropboxUnlinkedException e) { 
       Log.e("DbExampleLog", "User has unlinked."); 
      } catch (DropboxException e) { 
       Log.e("DbExampleLog", "Something went wrong while uploading."); 
      } 
+7

co jest mDBApi w tym kodzie? – TharakaNirmana

+1

Wiem, że ta odpowiedź jest spóźniona, ale kto wie, może to uratować niektórych ludzi. Jest to zmienna globalna.To jest kod, który powinieneś dodać: prywatny DropboxAPI mDBApi; – Yenthe

+0

prywatny DropboxAPI mDBApi; – nikki

2

@ odpowiedź e-Nature jest więcej niż poprawna ... po prostu pomyślałem, że każdy punkt na oficjalnej stronie, że Dropbox pokazuje, jak wykonać upload a file and much more.

Ponadto, odpowiedź @ e-natura zastępuje pliki o tej samej nazwie, więc jeśli nie chcesz tego zachowania, po prostu użyj .putFile zamiast .putFileOverwrite. .putFile ma dodatkowy argument, możesz po prostu dodać wartość null do końca. More info.

5

Oto kolejna realizacja Dropbox API do przesłania i pobrania akta. Można to zaimplementować dla dowolnego typu pliku.

String file_name = "/my_file.txt"; 
String file_path = Environment.getExternalStorageDirectory() 
     .getAbsolutePath() + file_name; 
AndroidAuthSession session; 

public void initDropBox() { 

    AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET); 
    session = new AndroidAuthSession(appKeys); 
    mDBApi = new DropboxAPI<AndroidAuthSession>(session); 
    mDBApi.getSession().startOAuth2Authentication(MyActivity.this); 

} 

Entry response; 

public void uploadFile() { 
    writeFileContent(file_path); 
    File file = new File(file_path); 
    FileInputStream inputStream = null; 
    try { 
     inputStream = new FileInputStream(file); 
    } catch (FileNotFoundException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 


    try { 
     response = mDBApi.putFile("/my_file.txt", inputStream, 
       file.length(), null, null); 
     Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev); 
    } catch (DropboxException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 

    } 

} 
public void downloadFile() { 

    File file = new File(file_path); 
    FileOutputStream outputStream = null; 

    try { 
     outputStream = new FileOutputStream(file); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    DropboxFileInfo info = null; 
    try { 
     info = mDBApi.getFile("/my_file.txt", null, outputStream, null); 



     Log.i("DbExampleLog", "The file's rev is: " 
       + info.getMetadata().rev); 
    } catch (DropboxException e) { 
     // TODO Auto-generated catch block 

     e.printStackTrace(); 
    } 

} 

@Override 
    protected void onResume() { 
     // TODO Auto-generated method stub 
     super.onResume(); 
     if (mDBApi.getSession().authenticationSuccessful()) { 
      try { 
       // Required to complete auth, sets the access token on the 
       // session 

      mDBApi.getSession().finishAuthentication(); 

      String accessToken = mDBApi.getSession().getOAuth2AccessToken(); 

      /** 
      * You'll need this token again after your app closes, so it's 
      * important to save it for future access (though it's not shown 
      * here). If you don't, the user will have to re-authenticate 
      * every time they use your app. A common way to implement 
      * storing keys is through Android's SharedPreferences API. 
      */ 

     } catch (IllegalStateException e) { 
      Log.i("DbAuthLog", "Error authenticating", e); 
     } 
    } 
} 

-> Połączenie uploadFile() i downLoadFile() metoda w wątku dziecko inaczej to daje wyjątek

-> dla danego zastosowania AsyncTask i nazywają te powyżej metody w doInBackground metoda.

nadzieję, że będzie pomocny ... Dzięki

2

Oto kolejny przykład, który korzysta z API v2 Dropbox ale 3rd party SDK. Działa to dokładnie tak samo na Dysku Google, OneDrive i Box.com.

// CloudStorage cs = new Box(context, "[clientIdentifier]", "[clientSecret]"); 
// CloudStorage cs = new OneDrive(context, "[clientIdentifier]", "[clientSecret]"); 
// CloudStorage cs = new GoogleDrive(context, "[clientIdentifier]", "[clientSecret]"); 
CloudStorage cs = new Dropbox(context, "[clientIdentifier]", "[clientSecret]"); 
new Thread() { 
    @Override 
    public void run() { 
     cs.createFolder("/TestFolder"); // <--- 
     InputStream stream = null; 
     try { 
      AssetManager assetManager = getAssets(); 
      stream = assetManager.open("UserData.csv"); 
      long size = assetManager.openFd("UserData.csv").getLength(); 
      cs.upload("/TestFolder/Data.csv", stream, size, false); // <--- 
     } catch (Exception e) { 
      // TODO: handle error 
     } finally { 
      // TODO: close stream 
     } 
    } 
}.start(); 

Używa CloudRail Android SDK

Powiązane problemy