19

如何使用 Dropbox API 通过 Android 将文件(图形、音频和视频文件)上传到 Dropbox?我遵循了Dropbox SDK Android页面上的教程,并且可以让示例正常工作。但是现在我想上传一个实际的 File 对象而不是 String 并且正在苦苦挣扎。

示例代码可以正常工作,如下所示:

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

但是当我尝试更改它并使用此代码上传实际文件时:

    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 对象转换为字节流的地方一定是错误的,但这只是一个假设。

除了 String 示例之外,Android 的 Dropbox 页面上没有其他任何文档记录。

谢谢你的帮助。

4

5 回答 5

24

我找到了解决方案 - 如果有人对这里感兴趣是工作代码:

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.");
            }
于 2012-03-23T01:08:24.377 回答
6

这是另一个用于上传下载文件的Dropbox API实现。这可以为任何类型的文件实现。

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

-> 在子线程中调用 uploadFile() 和 downLoadFile() 方法,否则会给你异常

-> 为此使用 AsyncTask 并在 doInBackground 方法中调用上述方法。

希望这会有所帮助...谢谢

于 2015-06-18T04:48:53.917 回答
3

这是另一个使用 Dropbox v2 API 但使用 3rd 方 SDK 的示例。顺便说一句,它对 Google Drive、OneDrive 和 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();

它使用CloudRail Android SDK

于 2016-08-22T16:27:48.790 回答
2

@e-nature 的回答非常正确……只是想我会把每个人都指向 Dropbox 的官方网站,该网站展示了如何上传文件等等

此外,@e-nature 的答案会覆盖具有相同名称的文件,因此如果您不希望这种行为,只需使用.putFile而不是.putFileOverwrite. .putFile有一个额外的参数,您可以简单地将 null 添加到末尾。更多信息

于 2013-01-13T23:37:08.370 回答
2

根据 dropbox API V2 的最新文档:

// Create Dropbox client
    val config = DbxRequestConfig.newBuilder("dropbox/java-tutorial").build()
    client = DbxClientV2(config, getString(R.string.token))

// Uploading file
    FileInputStream(file).use { item ->
        val metadata = client.files().uploadBuilder("/${file.absolutePath.substringAfterLast("/")}")
                .uploadAndFinish(item)
    }

如果要覆盖文件,请将其添加到客户端:

.withMode(WriteMode.OVERWRITE)
.uploadAndFinish(item)
于 2020-03-20T11:10:03.327 回答