使用Dropbox API上传Android文件

时间:2023-01-27 11:54:14

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.

如何使用Dropbox API将文件(图形,音频和视频文件)上传到Dropbox?我按照Dropbox SDK Android页面上的教程进行操作,可以使样本生效。但是现在我要上传一个实际的File对象而不是String,而且我正在努力。

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.

我没有成功收到DropboxException错误。我认为我尝试将File对象转换为字节流的东西必定是错误的,但这只是一个假设。

Other than the String example there is nothing else documented on the Dropbox page for Android.

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

Thanks for any help.

谢谢你的帮助。

4 个解决方案

#1


23  

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

#2


5  

Here is another implementation of Dropbox API to upload and download a file. This can be implemented for any type of file.

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

->Call uploadFile() and downLoadFile() method in child thread otherwise it will give you exception

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

->For that use AsyncTask and call these above method in doInBackground method.

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

Hope this will be helpful...Thanks

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

#3


2  

@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.

@ e-nature的答案不仅仅是正确的...只是想我会把所有人都指向Dropbox的官方网站,该网站展示了如何上传文件等等。

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.

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

#4


2  

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.

这是使用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();

It uses the CloudRail Android SDK

它使用CloudRail Android SDK

#1


23  

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

#2


5  

Here is another implementation of Dropbox API to upload and download a file. This can be implemented for any type of file.

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

->Call uploadFile() and downLoadFile() method in child thread otherwise it will give you exception

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

->For that use AsyncTask and call these above method in doInBackground method.

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

Hope this will be helpful...Thanks

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

#3


2  

@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.

@ e-nature的答案不仅仅是正确的...只是想我会把所有人都指向Dropbox的官方网站,该网站展示了如何上传文件等等。

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.

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

#4


2  

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.

这是使用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();

It uses the CloudRail Android SDK

它使用CloudRail Android SDK