I have the following code, it creates a file on a remote server from a test var (just to make sure it worked), but now I need to upload a file and I'm not sure how to actually attach it to the request, here is the code:
var dataString = '@test.txt';
var options = {
uri: 'https://site.zendesk.com/api/v2/uploads.json?filename=test.txt',
method: 'POST',
headers: {
'Content-Type': 'application/binary',
'Accept': 'application/json',
Authorization: 'Basic bXVydGV6LmF....'
},
body: dataString
//this will create a test file with some text, but I need
//to upload a file on my machine instead
}
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
var x = {
error: error,
response: response,
body: body
}
console.log(x);
}
request(options, callback);
I was thinking something in the lines of:
fs.createReadStream('text.txt').pipe({function?})
But I'm not sure how to finish this part unfortunately.
update: 2019 It's been a LONG time, but someone asked for the solution. I'm not sure if this is how I fixed it tbh or if this code even works, but I found this digging around, give it a try.
Also, Zendesk updated their API at some point, not sure when exactly so this may be old anyways:
var uploadAttachment = function() {
var uOptions = {
uri: 'xxx/api/v2/uploads.json?filename=' + fileName,
method: 'POST',
headers: {
'Content-Type': 'application/binary',
'Accept': 'application/json',
Authorization: 'Basic xxx'
}
};
function callback(error, response, body) {
if (!body) {
if (error) {
return next(error);
} else {
var x = {
error: true,
message: "Some message",
err: response
};
return next(x);
}
}
if (body && body.error) {
return next(error);
}
if (error) {
return next(error);
}
var jr = JSON.parse(body);
var uploaded = {};
if (jr.upload) {
uploaded = jr.upload;
}
attachToComment(uploaded);
}
fs.createReadStream(tempPath + fileName).pipe(request(uOptions, callback));
};
I hope this helps, sorry in advance if it does not work, I no longer have access to zendesk.