You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中接入Dropbox API并实现文件夹上传?

Hey there! Since you’ve got experience uploading to Firebase, you’ll find integrating Dropbox API in Flutter totally manageable—let’s walk through everything step by step, no jargon overload.

Step 1: Set Up Your Dropbox Developer Account & App

First, you need to get your app credentials from Dropbox:

  • Head to the Dropbox Developer Console and create a new app. Pick "Scoped access" and choose either "Full Dropbox" (access to all of a user’s Dropbox) or "App folder" (restricted to a dedicated folder for your app—great for testing).
  • Go to the Permissions tab and enable the files.content.write permission—this lets your app upload files and folders to Dropbox.
  • Grab your App Key and App Secret from the Settings tab—you’ll need these later for authentication.
Step 2: Add the Dropbox Flutter Package

We’ll use a popular community package to simplify integration. Add this to your pubspec.yaml:

dependencies:
  dropbox_client: ^1.0.0 # Make sure to use the latest version

Run flutter pub get to install it.

Step 3: Authenticate Your App

There are two ways to authenticate—one for quick testing, one for production:

Option 1: Temporary Access Token (Testing Only)

For fast testing, generate a temporary access token in your Dropbox app’s Settings tab (it expires after 4 hours). Initialize the client like this:

import 'package:dropbox_client/dropbox_client.dart';

void initDropbox() async {
  await Dropbox.init(
    'YOUR_APP_KEY',
    'YOUR_APP_SECRET',
    'YOUR_TEMP_ACCESS_TOKEN', // Paste the generated token here
  );
}

Option 2: OAuth Authentication (Production Ready)

For real users, you’ll need to let them log in with their Dropbox account. Here’s a basic implementation:

import 'package:dropbox_client/dropbox_client.dart';
import 'package:shared_preferences/shared_preferences.dart';

Future<void> authenticateWithDropbox() async {
  final authResult = await Dropbox.authorize();
  
  if (authResult.isSuccessful) {
    final accessToken = authResult.accessToken;
    // Save the token securely (use shared_preferences or a secure storage package)
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('dropbox_access_token', accessToken);
    
    // Initialize the client with the saved token
    await Dropbox.init('YOUR_APP_KEY', 'YOUR_APP_SECRET', accessToken);
  } else {
    print('Authentication failed: ${authResult.error}');
    // Handle error (show snackbar, alert, etc.)
  }
}
Step 4: Upload a Folder to Dropbox

Dropbox API doesn’t have a single "upload folder" endpoint—you’ll need to upload each file in the folder recursively, preserving the structure. Here’s how to do it:

First, Get All Files from the Local Folder

Use path_provider to access device storage and fetch all files in your target folder:

import 'package:path_provider/path_provider.dart';
import 'dart:io';

Future<List<File>> getAllFilesInLocalFolder(String localFolderPath) async {
  final directory = Directory(localFolderPath);
  final List<File> files = [];

  if (await directory.exists()) {
    // List all files recursively
    final entities = directory.listSync(recursive: true);
    for (var entity in entities) {
      if (entity is File) {
        files.add(entity);
      }
    }
  }
  return files;
}

Then, Upload Each File to Dropbox

Loop through the files, build the corresponding Dropbox path, and upload each one:

Future<void> uploadFolderToDropbox(String localFolderPath, String dropboxDestinationPath) async {
  // Create the destination folder in Dropbox first (if it doesn't exist)
  await Dropbox.createFolder(dropboxDestinationPath);
  
  final files = await getAllFilesInLocalFolder(localFolderPath);
  
  for (var file in files) {
    // Get the relative path of the file to preserve folder structure
    final relativePath = file.path.replaceFirst(localFolderPath, '');
    final dropboxFilePath = '$dropboxDestinationPath$relativePath';

    // Upload the file
    final uploadResult = await Dropbox.upload(
      file.path,
      dropboxFilePath,
      mode: UploadMode.overwrite, // Choose overwrite or add (for duplicates)
    );

    if (uploadResult.isSuccessful) {
      print('Uploaded successfully: $dropboxFilePath');
    } else {
      print('Failed to upload $dropboxFilePath: ${uploadResult.error}');
    }
  }
}
Step 5: Handle Permissions & Edge Cases
  • Storage Permissions: On Android, add <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> to your AndroidManifest.xml. On iOS, add NSPhotoLibraryUsageDescription to Info.plist to explain why you need access to files.
  • Error Handling: Add checks for missing local folders, network issues, or invalid Dropbox paths. For large folders, consider adding progress indicators (the dropbox_client package supports progress callbacks if you need them).
  • Folder Creation: Always create the destination folder in Dropbox before uploading files—otherwise, uploads will fail if the path doesn’t exist.
Quick Comparison to Firebase

Since you’re used to Firebase, here’s a quick note:

  • Firebase Storage lets you upload folders implicitly, but Dropbox requires you to handle each file individually and create folders manually.
  • Authentication works differently: Firebase uses its own auth SDKs, while Dropbox relies on OAuth 2.0 (or temporary tokens for testing).

内容的提问来源于stack exchange,提问作者Haseeb Ahmed Rauf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:12:01