Built.io Blog

File Uploading in Dropbox using its API and Node.js

,

File Uploading in Dropbox using its API and Node.js

In this post, I will explain how to upload files in Dropbox using Node.js in four easy steps:

  1. Register your application in the Dropbox API
  2. Create an Authentication code for Dropbox
  3. Create a page for redirecting upon successful authentication
  4. Upload file

Register your application in the Dropbox API

Create your app in the Dropbox Developer Dashboard. While creating your app, provide the redirect URL, which will be used to redirect the user upon successful authentication.

After creating your app, you will obtain an app key and an app secret. This will be useful for authenticating your app. To register your API in Drobox, visit the developer portal.

Create an Authentication code for Dropbox

For authentication in Dropbox, you need an app key, a redirect URI, and a csrfToken. The app key is used for authentication of the app and can be retrieved when registering your application. The redirect URI is the URL provided during app creation.

function generateRedirectURI(req) {
return url.format({
    protocol: req.protocol,
    host: req.headers.host,
    pathname: app.path() + '/success'
});
}

The csrfToken is used to protect against cross-site request forgery (CSRF).

function generateCSRFToken() {
return crypto.randomBytes(18).toString('base64')
    .replace(///g, '-').replace(/+/g, '_');
}

The request for Dropbox authenication is done using the following code:

app.get('/', function (req, res) {
var csrfToken = generateCSRFToken();
res.cookie('csrf', csrfToken);
res.redirect(url.format({
    protocol: 'https',
    hostname: 'www.dropbox.com',
    pathname: '1/oauth2/authorize',
    query: {
        client_id: APP_KEY,//App key of dropbox api
        response_type: 'code',
        state: csrfToken,
        redirect_uri: generateRedirectURI(req)
    }
}));
});

Once the app is authenticated, it will redirect to the login page and ask the user for credentials. For further information about authorizing a Dropbox app, visit Dropbox's documentation on OAuth 2.0.

Create a page for redirecting upon successful authentication

On a successful login, allowing the user to use the app, an API is created for retrieving the token for the user. The following is a snippet of the code for getting a token:

app.get('/success', function (req, res) {
if (req.query.error) {
    return res.send('ERROR ' + req.query.error + ': ' + req.query.error_description);
}
if (req.query.state !== req.cookies.csrf) {
    return res.status(401).send(
        'CSRF token mismatch, possible cross-site request forgery attempt.'
    );
}
request.post('https://api.dropbox.com/1/oauth2/token', {
    form: {
        code: req.query.code,
        grant_type: 'authorization_code',
        redirect_uri: generateRedirectURI(req)
    },
    auth: {
        user: APP_KEY,
        pass: APP_SECRET
    }
}, function (error, response, body) {
    var data = JSON.parse(body);
    if (data.error) {
        return res.send('ERROR: ' + data.error);
    }
    var token = data.access_token;
    req.session.token=data.access_token;
    request.post('https://api.dropbox.com/1/account/info', {
        headers: { Authorization: 'Bearer ' + token }
    }, function (error, response, body) {
        res.send('Logged in successfully as ' + JSON.parse(body).display_name + '.');
    });
});
});

This step completes the authentication process and provides the token, which is used for further operation. For details about the Dropbox API, and getting the token, read Dropbox's OAuth Token documentation.

Upload File

To upload a file, use the following URL: https://api-content.dropbox.com/1/files_put/auto/<path>?param=val.

The <path> is the path of the Dropbox server where it will be saved. You can use a normal Node.js file upload the code, but you need to make some slight changes. Content-Type needs to be changed to text/plain from multipart/form-data. The multipart/form-data.content information along with boundary will be treated as file content. They need to be added in file content as follows:

 ----------------------------896458993824206159208557
Content-Disposition: form-data; name="upload[upload]"; filename="file3.js"
Content-Type: application/javascript
......
.....
File content
......
......
 ----------------------------896458993824206159208557—

Hence, to remove the extra information from the file content, Content-type needs to be changed to text/plain. The following is the code for file upload in Dropbox:

app.get('/uploadfile', function (req, res) {
var serverpath;//file to be save at what path in server
var localpath;//path of the file which is to be uploaded
if (req.query.error) {
    return res.send('ERROR ' + req.query.error + ': ' + req.query.error_description);
}
fs.readFile(localpath,'utf8', function read(err, data) {
        if (err) {
            throw err;
        }
        content = data;
        console.log(content); 
        fileupload(req.session.token,content);
    });
});
function fileupload(token,content){
    request.put('https://api-content.dropbox.com/1/files_put/auto/'+serverpath?overwrite, {
    headers: { Authorization: 'Bearer ' + token ,  'Content-Type': 'text/plain'
    },body:content}, function optionalCallback (err, httpResponse, bodymsg) {
    if (err) {
        console.log(err);
    }
    else
    { 
        console.log(bodymsg);
    }
});
}

So, we were initially reading the file, but once we completed the code, we could add the content as the body of the PUT request.

For further information on Dropbox’s file uploading API, visit Dropbox's documentation. For uploading larger files, you can use the chunk concept on Dropbox.

Subscribe to our blog