From 7b7942e7922d271e993ae4b2eeab8396d5f03be2 Mon Sep 17 00:00:00 2001 From: Michael Richardson <40401643+mdrichardson@users.noreply.github.com> Date: Wed, 13 Mar 2019 14:28:04 -0700 Subject: [PATCH] [JS Sample 15] Fix for image attachments (#1323) --- .../javascript_nodejs/15.handling-attachments/bot.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/samples/javascript_nodejs/15.handling-attachments/bot.js b/samples/javascript_nodejs/15.handling-attachments/bot.js index 9c03587272..bee342d77a 100644 --- a/samples/javascript_nodejs/15.handling-attachments/bot.js +++ b/samples/javascript_nodejs/15.handling-attachments/bot.js @@ -84,7 +84,16 @@ class AttachmentsBot { const localFileName = path.join(__dirname, attachment.name); try { - const response = await axios.get(url); + // arraybuffer is necessary for images + const response = await axios.get(url, { responseType: 'arraybuffer' }); + // If user uploads JSON file, this prevents it from being written as "{"type":"Buffer","data":[123,13,10,32,32,34,108..." + if (response.headers['content-type'] === 'application/json') { + response.data = JSON.parse(response.data, (key, value) => { + return value && value.type === 'Buffer' ? + Buffer.from(value.data) : + value; + }); + } fs.writeFile(localFileName, response.data, (fsError) => { if (fsError) { throw fsError;