How do I upload a binary file from Meteor to an external API?

时间:2016-02-03 03:25:44

标签: javascript meteor zendesk

My issue: I can't figure out how to send a binary file from a Base64 encoded string in my Meteor Methods using the Zendesk API.

Basically I'm trying to replicate this curl command in Meteor on the server side:

curl -u username:password -H "Content-Type: application/binary" --data-binary @file.dat -X POST "https://helpdesk.zendesk.com/api/v2/uploads.json?filename=myfile.dat&token={optional_token}"

I am getting a Base64 encoded file from the front-end. Here's my Meteor method:

http://pastie.org/private/irextwfhdbgpknjpjjldw

The upload works but the image is corrupted and I can't open it.

I'm still very new to Meteor and also pretty green about encoding and such, any help appreciated!

1 个答案:

答案 0 :(得分:0)

好吧,我找到了解决问题的方法。

我从原生Meteor HTTP切换到Node请求包。它似乎更支持发送二进制数据。也许我没有正确使用它,但无论我做什么,Meteor HTTP Call都会以奇怪的格式编码我的文件。

所以现在我使用这个辅助函数解码base64 dataString:

$conditions = array('Model.id' => $this->request->data['Model']['id'],
        'Model.field2' => $this->request->data['Model']['field2']);
$options['conditions'] = $conditions;

$this->Paginator->settings = $options;
$data = $this->Paginator->paginate('Model');

$this->set('views', $data);

然后我设置了选项

    function decodeBase64Image(dataString) {
        var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
            response = {};

        if (matches.length !== 3) {
            return new Error('Invalid input string');
        }

        response.type = matches[1];
        response.data = new Buffer(matches[2], 'base64');

        return response;
    }

我使用请求发布:

options = {
    headers: { 'content-type' : 'application/binary', 'Authorization': 'Basic ' + encoded },
    url: zendeskURI + 'uploads.json?filename=' + args.name,
    body: decodeBase64Image(file).data,
    method: 'POST'
};

现在一切正常,我可以将二进制数据上传到Zendesk API!