2

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"?

brandly
  • 86
  • 4
  • 8

2 Answers2

1

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);
Jonathan Wiepert
  • 1,222
  • 12
  • 12
  • I tried doing this, but I still got a "invalid_request_parameters" error. I'm not familiar with this request syntax. What all should be passed into request.post? – brandly Apr 26 '13 at 18:46
  • Also, I've checked out [this post](http://stackoverflow.com/questions/13797670/nodejs-post-request-multipart-form-data) which appears to be interacting with Box, though they don't mention it. They're using the `restler` module, which looks nice and simple, but I'm still not sure how to get a string read as a file. – brandly Apr 26 '13 at 19:13
  • I don't use box, but a quick loom at the docs, I think you want: { uri: 'https://api.box.com/2.0/files/content', headers: { Authorization: 'Bearer ' + authToken } } – Jonathan Wiepert Apr 26 '13 at 21:36
  • Sorry, that should be `{ uri: 'https://api.box.com/2.0/files/content';, headers: { Authorization: 'Bearer ' + authToken } }` . In request, you use uri since it is a fully qualified URI. url is used for parsed url object from url.parse(). – Jonathan Wiepert Apr 26 '13 at 21:41
0
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')));
mungi
  • 9
  • 1