2012-03-22 12 views
19

¿Cómo puedo cargar un archivo (archivo de gráficos, audio y video) con Android usando la API de Dropbox a Dropbox? Seguí el tutorial en la página Dropbox SDK Android y pude hacer que la muestra funcionara. Pero ahora, en lugar de una Cadena, quiero cargar un objeto de Archivo real y estoy luchando.Uso de la API de Dropbox para cargar un archivo con Android

El código de ejemplo funciona sin ningún problema y se ve así:

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."); 
} 

Pero cuando trato de cambiarlo y cargar un archivo real con este código:

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."); 
} 

tengo ningún éxito obteniendo un error DropboxException. Creo que algo en lo que intento convertir el objeto File a byte-stream debe ser incorrecto, pero esto es solo una suposición.

Aparte del ejemplo de String, no hay nada más documentado en la página de Dropbox para Android.

Gracias por cualquier ayuda.

Respuesta

23

he encontrado la solución - si alguien está interesado aquí es el código de trabajo:

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

lo que es mDBApi en este código? – TharakaNirmana

+1

Sé que esta respuesta es tardía, pero quién sabe podría salvar a algunas personas. Es una variable global.Este es el código que debe agregar: DropboxAPI privado mDBApi; – Yenthe

+0

privado DropboxAPI mDBApi; – nikki

2

@ respuesta de e-naturaleza es más que correcto ... sólo pensé en señalar a todos al sitio oficial de Dropbox que muestra cómo upload a file and much more.

Además, la respuesta de @e-nature sobrescribe los archivos con el mismo nombre, por lo que si no desea ese comportamiento simplemente use .putFile en lugar de .putFileOverwrite. .putFile tiene un argumento adicional, simplemente puede agregar nulo hasta el final. More info.

5

Aquí es otra implementación de la API de Dropbox a carga y descarga un archivo. Esto puede implementarse para cualquier tipo de archivo.

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

-> Llamada uploadfile() y el método de hilo hijo DownloadFile() sino que le dará excepción

-> Para que el uso AsyncTask y llamar a éstos por encima de método en el doInBackground método.

la esperanza que esto sea útil ... Gracias

2

Este es otro ejemplo que utiliza la versión 2 del API de Dropbox, sino una tercera parte del SDK. Por cierto, funciona exactamente igual para Google Drive, OneDrive y 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(); 

Utiliza el CloudRail Android SDK

Cuestiones relacionadas