Using Dropbox API to upload a file with Android

前端 未结 5 501
庸人自扰
庸人自扰 2020-12-08 15:31

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

相关标签:
5条回答
  • 2020-12-08 16:23

    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.

    // 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

    0 讨论(0)
  • 2020-12-08 16:24

    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.");
                }
    
    0 讨论(0)
  • 2020-12-08 16:26

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

    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

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

    Hope this will be helpful...Thanks

    0 讨论(0)
  • 2020-12-08 16:29

    According to the latest documentation of 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)
        }
    

    And if you want to overwrite file then add this to client:

    .withMode(WriteMode.OVERWRITE)
    .uploadAndFinish(item)
    
    0 讨论(0)
  • 2020-12-08 16:37

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

    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.

    0 讨论(0)
提交回复
热议问题