Bruno Monteiro
Bruno Monteiro

Reputation: 4519

How do I specify data-binary in Titanium Appcelerator?

I am trying to use the Dropbox API to upload a file. Here is the documentation from Dropbox:

curl -X POST https://content.dropboxapi.com/2/files/upload \
    --header "Authorization: Bearer <get access token>" \
    --header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}" \
    --header "Content-Type: application/octet-stream" \
    --data-binary @local_file.txt

I have this in my Appcelerator project:

var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
    //My function
};
xhr.open('POST','https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'My Key');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', '{"path":"/my_path/file.txt","mode":{".tag":"add"}}');

But I can't figure out how to send the data-binary argument. With my current code I can create a file in my Dropbox folder, but is just an empty file.

Upvotes: 1

Views: 345

Answers (2)

Bruno Monteiro
Bruno Monteiro

Reputation: 4519

I figure out a way to do that. In my case I just need to upload a simple data structure, so I am using a JSON object:

var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
    //My function
};
xhr.open('POST','https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'My Key');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', '{"path":"/my_path/file.txt","mode":{".tag":"add"}}');

var my_json = {
    "item1" : "content1"
};

xhr.send(JSON.stringify(my_json));

I still can't send a BLOB (like a picture from the phone gallery), but it works if you pass the path of the file:

var my_path = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory,'my_folder');
var newFile = Titanium.Filesystem.getFile(my_path.nativePath,'file.txt');
newFile.createFile();
newFile.write('Content of my text file');

var params = {"data-binary" : newFile};
xhr.send(params);

Upvotes: 0

user94559
user94559

Reputation: 60143

From http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network.HTTPClient, it looks like you just pass it into xhr.send(). You can pass a string, an object (which gets form-encoded), or a Titanium.Blob.

(Disclaimer: I've never used Appcelerator, so this is just what I surmise from reading the documentation.)

Upvotes: 0

Related Questions