Logo with initials
Click me x5 ↓

Upload a file (to Dropbox) with Node.js

Last updated: January 9, 2023

Run it with node upload.js --file="My file.mp4"

We’re using the native fetch API that is available in Node.js 18+.

Two concepts here:

  • Uploading a local file to a server using fetch, fs and Promises. This works whether it’s to Dropbox or not.
  • Using the files/upload endpoint of the Dropbox API, which only accepts files that are less than 150MB.

Otherwise the upload process is more complicated and involves breaking the file into multiple chunks. Which is not what we’re doing here.

// upload.js
import fs from 'node:fs/promises';
import parser from 'yargs-parser';

const start = async () => {
  // parse the filename from the command line
  const args = parser(process.argv.slice(2));
  const { file } = args;

  // read the file
  const data = await fs.readFile(file);
  console.log('file read', file);

  const res = await fetch('https://content.dropboxapi.com/2/files/upload', {
    method: 'post',
    body: data,
    headers: {
      Authorization: `Bearer ${YOUR_API_TOKEN}`,
      'Dropbox-API-Arg': JSON.stringify({
        // this is the path to the file in dropbox within your app's folder
        // So, if your Dropbox app is called "MyApp", the path will be "/MyApp/${file}"
        // you can change it to something like "/MyApp/my-uploads/${file}"
        path: `/${file}`,
        // overwrite if there's already a file with the same name
        mode: 'overwrite',
        autorename: true,
      }),
      'Content-Type': 'application/octet-stream',
    },
  });
};

start()
  .then(() => {
    console.log('File uploaded!');
  })
  .catch((err) => {
    console.log(err);
  });

The full repo is available here on Github

Cheers, Alvin