19

Dropbox APIを使用してAndroidでファイル(グラフィック、オーディオ、ビデオファイル)をDropboxにアップロードするにはどうすればよいですか?Dropbox SDK Androidページのチュートリアルに従い、サンプルを動作させることができました。しかし、文字列の代わりに、実際のFileオブジェクトをアップロードしたいので、苦労しています。

サンプルコードは問題なく動作し、次のようになります。

    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オブジェクトをバイトストリームに変換しようとするものは間違っているに違いないと思いますが、これは単なる仮定です。

文字列の例を除いて、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

これは、ファイルをアップロードおよび ダウンロードするためのDropboxAPIの別の実装です。これは、あらゆるタイプのファイルに実装できます。

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を使用しているが、サードパーティのSDKを使用している別の例です。ちなみに、Googleドライブ、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();

CloudRailAndroidSDKを使用します

于 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 に答える