从附件中获取图像作为 Arraybuffer 后,如何使用 Axios post 图像作为文件

How to post an image as a File with Axios after Getting it as an Arraybuffer from an attachment

作为 POC,我想为我的收据(汽油、商店等)拍照,并使用聊天机器人将它们发送到我的会计软件。我的问题与使用 API.

将收集到的收据(图像)发送到会计软件有关

第一部分(获取附件)生成带有图像的 Arraybuffer。我为此使用了一个 NodeJS 示例 (nr 15)。

    const attachment = turnContext.activity.attachments[0];
    const url = attachment.contentUrl;
    let image;
    axios.get(url, { responseType: 'arraybuffer' })
        .then((response) => {
            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;
                });
            }
            image = response.data;
        }
        ).catch((error) => {
            console.log(error);
        });

我正在为第二部分而苦苦挣扎。将图像发布到会计软件

const requestConfig = {
        headers: {
            'Authorization': 'Bearer ' + accessToken,
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    };
    axios.post(postUrl, image, requestConfig)
        .then((response) => { console.log(response); }
        ).catch((error) => {
            console.log(error);
        });
};

这导致 400. 错误请求。可能 API 需要一个文件,我不能只发送缓冲区。我使用 Postman 进行了测试,使用 application/x-www-form-urlencoded(通过使用本地存储的图像文件)接受了请求。

post 在缓冲区数组中检索图像的最佳做法是什么?

我认为您的评论是正确的,因为您需要先将其转换为文件。频道不是问题,因为文件将存储在托管机器人的任何地方。 Attachments Sample actually has this code,让你接近:

fs.writeFile(localFileName, response.data, (fsError) => {
    if (fsError) {
        throw fsError;
    }
    // Send the file
    const url = '<yourApiUrl>';
    const formData = new FormData();
    formData.append('file',fs.createReadStream('<pathToFile>'), { knownLength: fs.statSync('<pathToFile>').size });
    const config = {
        headers: {
            ...formData.getHeaders(),
            'Content-Length': formData.getLengthSync()
        }
    };
    axios.post(url, forData, { headers });
});

我对 // Send the file 部分不是很有信心,只是因为我无法针对您的 API 进行测试。我从 here.

获得了大部分代码