Integrating Dropbox API with Website
Dropbox API allows uploading and downloading files, managing folders, and creating shared links. Used as a file backend for websites: uploading user files to Dropbox, accessing media libraries, backups.
Authentication
import { Dropbox } from 'dropbox';
// For server operations: App-level token
const dbx = new Dropbox({ accessToken: process.env.DROPBOX_ACCESS_TOKEN });
// For user operations: OAuth2 flow
Uploading File
async function uploadFile(filePath: string, fileContent: Buffer): Promise<string> {
const resp = await dbx.filesUpload({
path: filePath, // '/uploads/documents/contract.pdf'
contents: fileContent,
mode: { '.tag': 'add' },
autorename: true, // if file exists — adds (1) to name
});
// Create temporary shared link
const linkResp = await dbx.sharingCreateSharedLinkWithSettings({
path: resp.result.path_display!,
settings: {
requested_visibility: { '.tag': 'public' },
expires: new Date(Date.now() + 7 * 86400000).toISOString(),
},
});
// Convert link for direct download
return linkResp.result.url.replace('www.dropbox.com', 'dl.dropboxusercontent.com').replace('?dl=0', '');
}
Chunked Upload for Large Files
async function chunkedUpload(filePath: string, data: Buffer): Promise<string> {
const CHUNK_SIZE = 8 * 1024 * 1024; // 8MB
// Start session
const session = await dbx.filesUploadSessionStart({
contents: data.slice(0, CHUNK_SIZE),
close: data.length <= CHUNK_SIZE,
});
let offset = CHUNK_SIZE;
while (offset < data.length) {
const chunk = data.slice(offset, offset + CHUNK_SIZE);
const isLast = offset + chunk.length >= data.length;
if (isLast) {
await dbx.filesUploadSessionFinish({
cursor: { session_id: session.result.session_id, offset },
commit: { path: filePath, mode: { '.tag': 'add' } },
contents: chunk,
});
} else {
await dbx.filesUploadSessionAppendV2({
cursor: { session_id: session.result.session_id, offset },
contents: chunk,
});
}
offset += CHUNK_SIZE;
}
return filePath;
}
Webhooks
Dropbox notifies about folder changes via webhooks — convenient for media library synchronization:
Route::post('/webhooks/dropbox', function (Request $request) {
$signature = $request->header('X-Dropbox-Signature');
$expected = hash_hmac('sha256', $request->getContent(), config('services.dropbox.app_secret'));
if (!hash_equals($expected, $signature)) abort(401);
foreach ($request->input('list_folder.accounts', []) as $accountId) {
SyncDropboxFolder::dispatch($accountId);
}
return response('ok');
});
Timeline
File upload/download with OAuth2: 2–3 business days.







