Logo with initials

Upload a file (to Dropbox) with Node.js

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

We’re using the fetch API with node-fetch.

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 Dropbox files/upload endpoint, 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
const fs = require('fs').promises;
const fetch = require('node-fetch');
// parse the filename from the command line
const args = require('yargs-parser')(process.argv.slice(2));
const { file } = args;

const start = async () => {
  // read the file
  const data = await fs.readFile(file);
  console.log('file read');

  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,
        mute: false,
        strict_conflict: false,
      }),
      'Content-Type': 'application/octet-stream',
    },
  });
};

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