I am trying to download a Attachment using JSForce library. I am able to get body of attachment and download that file but somehow content of downloaded file is not correct and I am getting a corrupt downloaded file.
var conn = new jsforce.Connection({
accessToken: `${this.sessionId}`
});
let query = 'select id, body, name from attachment where id = \'00P1g000005A1mT\'';
conn.query(query, function(err, res) {
console.log(res.records[0]);
if(res) {
conn.chatter.resource(res.records[0].Body).retrieve(function(err,body) {
var l = btoa(unescape(encodeURIComponent(body)));
var blob = new Blob(l, {type: "image/jpeg"});
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'todo-1.jpg';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
alert('your file has downloaded!');
})
}
})
I am running above method in a LWC component. File downloaded is corrupted. I think mistake I am making is somehow how I am converting body to blob but I am not able to figure it out. I also tried getting body of attachment using stream
var stream = conn.sobject('Attachment').record(res.records[0].Id).blob('Body');
var result = [];
stream.on('data', function(chunk) {
result.push(chunk);
console.log(chunk);
});
stream.on('end', function () {
});
But Stream.on( events is not getting fired. Sometime 'data' event fires but end event don't fire ever.