SDK Platform: Node.js
How can I upload file (.pdf,.jpg..jpeg) from bot Emulator and convert to binary (base64) without saving file into local drive.
Code Example:
var url = session.message.attachments[0].contentUrl;
var fileName=session.message.attachments[0].name;
var encodedData = new Buffer(fs.createWriteStream(url+"/"+fileName), 'binary').toString('base64');
something like above, but it is not working for me.
Expected Behavior:
We need to upload file from BOT emulator and convert file content into binary data.
Actual Result:
ERROR: ENOENT: no such file or directory, open 'D:\\User\\projects\\messages\\http:\\localhost:61058\\v3\\attachments\\ne1gmlim5kfg\\views\\original\\filename.pdf'
Here appending current directory which is not required.
For reference: https://github.com/Microsoft/BotBuilder/issues/3628
Here's an example of downloading a file and base64 encoding it in memory:
var bot = new builder.UniversalBot(connector, function (session) {
var msg = session.message;
if (msg.attachments.length) {
// Message with attachment, proceed to download it.
// Skype & MS Teams attachment URLs are secured by a JwtToken, so we need to pass the token from our bot.
var attachment = msg.attachments[0];
var fileDownload = checkRequiresToken(msg) ? requestWithToken(attachment.contentUrl) : request(attachment.contentUrl);
fileDownload.then(
function (response) {
var base64String = new Buffer(response, 'binary').toString('base64');
var echoImage = new builder.Message(session).text('You sent:').addAttachment({
contentType: attachment.contentType,
contentUrl: 'data:' + attachment.contentType + ';base64,' + base64String,
name: 'Uploaded Image'
});
session.send(echoImage);
}).catch(function (err) {
console.log('Error downloading attachment:', { statusCode: err.statusCode, message: err.response.statusMessage });
});
} else {
// No attachments were sent
var reply = new builder.Message(session)
.text('Hi there! This sample is intented to show how can I receive attachments but no attachment was sent to me. Please try again sending a new message with an attachment.');
session.send(reply);
}
});
// Request file with Authentication Header
var requestWithToken = function (url) {
return obtainToken().then(function (token) {
return request({
url: url,
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/octet-stream'
}
});
});
};
// Promise for obtaining JWT Token (requested once)
var obtainToken = Promise.promisify(connector.getAccessToken.bind(connector));
var checkRequiresToken = function (message) {
return message.source === 'skype' || message.source === 'msteams';
};
An entire project demonstrating this can be found here: https://github.com/nwhitmont/botframework-node-v3-receive-attachment
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.