使用 Dropbox API 在 Android 上上传文件 [英] Using Dropbox API to upload a file with Android
问题描述
如何通过 Android 使用 Dropbox API 将文件(图形、音频和视频文件)上传到 Dropbox?我遵循了 Dropbox SDK Android 页面上的教程,可以让示例工作.但现在我想上传一个实际的 File 对象而不是 String 并且正在挣扎.
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.");
}
我没有成功收到 DropboxException 错误.我认为我尝试将 File 对象转换为字节流的地方一定是错误的,但这只是一个假设.
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.
除了 String 示例之外,Android 版 Dropbox 页面上没有其他任何记录.
Other than the String example there is nothing else documented on the Dropbox page for Android.
感谢您的帮助.
推荐答案
我找到了解决方案 - 如果有人感兴趣,这里是工作代码:
I found the solution - if anyone is interested here is the working code:
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.");
}
这篇关于使用 Dropbox API 在 Android 上上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!