简体   繁体   中英

How can I get the path of an excel file with nodeJS in a chatbot using Bot framework?

I have done a chatbot with bot framework and with this framework it is possible to add an attachement. So I have done a code to have my excel file in base64 after I add it in my chatbot.

But I want to take an Excel file from everywhere in my pc and to transform it in base64 I need to have the full path and in NodeJS I don't know how to do it.

 async attachmentsStep(stepContext, next) {
        var fs = require('fs');
        var activity = stepContext.context.activity;

        if (activity.attachments && activity.attachments.length > 0) {
            var attachment = activity.attachments[0];
            // function to encode file data to base64 encoded string
            function base64_encode(file) {
                // read binary data
                var bitmap = fs.readFileSync(file);
                // convert binary data to base64 encoded string
                return new Buffer.from(bitmap).toString('base64');
            }

            this.base64str = base64_encode( **PATH OF EXCEL FILE** + attachment.name);

            var nex = await stepContext.next();
            var base64 = this.base64str;

            return {
                base64,
                nex
            };
        } 
    }

Do you have an idea please?

You can use the __filename and__dirname for getting the file's absolute path.

console.log(__filename);
// Prints: /Users/mjr/example.js

ContentUrl recovers the file so not need the path and with the url I have directly convert it in base64 like this:

async attachmentsStep(stepContext, next) {
        var activity = stepContext.context.activity;

        if (activity.attachments && activity.attachments.length > 0) {
            var attachment = activity.attachments[0];

            var base64Url = attachment.contentUrl;
            console.log(process.env.PATH);

            /** Convert Url in base64 **/
            var axios = require('axios');
            var excel = await axios.get(base64Url, {responseType: 'arraybuffer'});
            var base64str = Buffer.from(excel.data).toString('base64');
            /**************************/

            // base64str = 'data:' + base64Type + ';base64,' + base64str; 

            var nex = await stepContext.next();              

            return {
                base64str,
                nex
            };
        }

    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM