Writing a file with the Dropbox JavaScript SDK

Posted by Steve Marx on December 17, 2013

I was recently asked for a "Hello World" example of writing a file to Dropbox using JavaScript. The Getting Started guide that comes with dropbox.js is probably the most complete resource for this, but in the true spirit of "Hello, World," I thought I'd share a minimal snippet to accomplish the task:

var client = new Dropbox.Client({ key: 'YOUR-APP-KEY-HERE' });
client.authenticate(function () {
    client.writeFile('hello.txt', 'Hello, World!', function () {
        alert('File written!');
    });
});

Note that you'll need to insert your own app key to run this code. This comes from creating an app in the App console. You'll also need to add an "OAuth redirect URI" in the App console. This has to exactly match the full URL of your running app.

A more realistic "Hello, World!"

The code above isn't extremely realistic, in a couple ways:

  1. It redirects the user to authenticate with Dropbox as soon as they visit the page.
  2. It doesn't handle any errors. Notably, the call to authenticate can fail under normal circumstances if the user clicks "Cancel" instead of "Allow" on the authorization page.

A better, more complete version of this code is below. This version only requires authentication when the user clicks the button, and this version also provides some error-handling. As a side note, I'm using the Datastore SDK here. You could instead use dropbox.js from GitHub instead. The Datastore SDK includes the same file functionality.

<!doctype html>
<html>
<head>
    <script src="https://www.dropbox.com/static/api/dropbox-datastores-1.0-latest.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <center>
        <button id="writeButton">Click to create <code>hello.txt</code> in Dropbox.</button>
    </center>

    <script>
        var client = new Dropbox.Client({ key: 'YOUR-APP-KEY-HERE' });

        function doHelloWorld() {
            client.writeFile('hello.txt', 'Hello, World!', function (error) {
                if (error) {
                    alert('Error: ' + error);
                } else {
                    alert('File written successfully!');
                }
            });
        }

        // Try to complete OAuth flow.
        client.authenticate({ interactive: false }, function (error) {
            if (error) {
                alert('Error: ' + error);
            } else {
                doHelloWorld();
            }
        });

        document.getElementById('writeButton').onclick = function () {
            client.authenticate(function (error, client) {
                if (error) {
                    alert('Error: ' + error);
                } else {
                    doHelloWorld();
                }
            });
        }
    </script>
</body>
</html>