How can I upload a File (graphic, audio and video file) with Android using the Dropbox API to Dropbox? I followed the tutorial on the Dropbox SDK Android page and could get the sample to work. But now instead of a String I want to upload an actual File object and am struggling.
The sample code works without any problems and looks like this:
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.");
}
But when I try to change it and upload an actual file with this code:
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.");
}
I have no success getting a DropboxException error. I think something where I try to convert the File object to the byte-stream must be wrong but this is just an assumption.
Other than the String example there is nothing else documented on the Dropbox page for Android.
Thanks for any help.
Here is another example which uses the Dropbox v2 API but a 3rd party SDK. It works exactly the same for Google Drive, OneDrive and Box.com by the way.
It uses the CloudRail Android SDK
@e-nature's answer is more than correct...just thought I'd point everyone to Dropbox's official site that shows how to upload a file and much more.
Also, @e-nature's answer overwrites files with the same name, so if you don't want that behaviour simply use
.putFile
instead of.putFileOverwrite
..putFile
has an extra argument, you can simply add null to to the end. More info.Here is another implementation of Dropbox API to upload and download a file. This can be implemented for any type of file.
->Call uploadFile() and downLoadFile() method in child thread otherwise it will give you exception
->For that use AsyncTask and call these above method in doInBackground method.
Hope this will be helpful...Thanks
I found the solution - if anyone is interested here is the working code: