使用Dropbox API在Android上上传文件

19

我该如何使用Dropbox API将文件(图形、音频和视频文件)上传到Dropbox?我按照Dropbox SDK Android页面上的教程进行了操作,成功地完成了示例。但是现在,我想上传一个实际的文件对象而不是一个字符串,并且遇到了困难。

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

    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错误。我认为在尝试将文件对象转换为字节流时出了些问题,但这只是一种假设。

除了String示例之外,在Dropbox Android页面上没有其他文档。

感谢任何帮助。

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

1
我知道这个答案有点晚了,但谁知道它可能会帮助到一些人。这是一个全局变量。这是你应该添加的代码: private DropboxAPI<AndroidAuthSession> mDBApi; - Yenthe
私有的DropboxAPI<AndroidAuthSession> mDBApi; - nikki
我正在寻找使用Sync API将音频文件上传到Dropbox。 - Ahmed Adel Ismail
假设我使用Intent选择了一个文件,那么我只需要将该文件上传到Dropbox,那么我该如何使用putFile方法? - user2056563

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方法中调用上述方法。

希望这对您有所帮助...谢谢


3

这是另一个使用Dropbox v2 API但第三方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

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)

2
@e-nature的回答绝对正确...我想指出一下Dropbox官方网站上有如何上传文件和更多内容的说明(链接)
此外,@e-nature的回答会覆盖同名文件,如果您不希望这种行为,只需使用.putFile而不是.putFileOverwrite.putFile有一个额外的参数,您可以在末尾添加null即可。更多信息

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接