brandly
brandly

Reputation: 86

Upload file to Box API from string using Node.js

I'm using version 2 of Box's API and attempting to upload files. I have Oauth 2 all working, but I'm having trouble making actual uploads.

I'm using Node.js and Express, along with the "request" module. My code looks something like this:

request.post({
  url: 'https://upload.box.com/api/2.0/files/content',
  headers: {
    Authorization: 'Bearer ' + authToken
  },
  form: {
    filename: ????,
    parent_id: '0'
  }
}, function (error, response, body) {
  // ...
});

For now, I'm trying to upload to the root folder which, if I understand correctly, has an ID of '0'.

What I'm really not sure about is what value to give "filename". I don't have a true file to read from, but I do have a lengthy string representing the file contents I would like to upload.

How best should I upload this "file"?

Upvotes: 2

Views: 2844

Answers (2)

mungi
mungi

Reputation: 9

var fs = require('fs');
var request = require('request');
var path = require('path');

function requestCallback(err, res, body) {
    console.log(body);
}

var accessToken = 'SnJzV20iEUw1gexxxxvB5UcIdopHRrO4';
var parent_folder_id = '1497942606';

var r = request.post({
    url: 'https://upload.box.com/api/2.0/files/content',
    headers: { 'Authorization': 'Bearer ' + accessToken }
    }, requestCallback);

var form = r.form();
form.append('folder_id', parent_folder_id);
form.append("filename", fs.createReadStream(path.join(__dirname, 'test.mp4')));

Upvotes: 0

Jonathan Wiepert
Jonathan Wiepert

Reputation: 1242

For Box, I believe you want to use requests multi-part/form-data implementation. It should look something like this:

var request = require('request');
var fs = require('fs');

var r = request.post(...);
var form = r.form();
form.append('filename', new Buffer("FILE CONTENTS"), {filename: 'file.txt'});
form.append('parent_id', 0);

Upvotes: 1

Related Questions