【问题标题】:How to post an image as a File with Axios after Getting it as an Arraybuffer from an attachment从附件获取图像作为 Arraybuffer 后如何使用 Axios 将图像作为文件发布
【发布时间】:2019-10-03 13:39:03
【问题描述】:

作为 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. bad request。可能 API 需要一个文件,而我不能只发送缓冲区。我用 Postman 进行了测试,并通过使用 application/x-www-form-urlencoded (通过使用本地存储的图像文件)接受了请求。

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

【问题讨论】:

  • 当您说“将图像发布到会计软件”时,您的意思是将图像发送到非botframework API?公共 API 是否可用?这应该会给你一些关于接受格式的线索。
  • @mdrichardson-MSFT 他们要求标头内容类型为:multipart/mixed。正文应包含一个文件。在 cURL 示例中,它声明:-F file=@/tmp/upload.pdf。猜猜我需要找到一种将arraybuffer转换为文件并发送的方法。没弄清楚怎么做。在 Facebook 频道的情况下,将 if 临时存储在文件系统上作为中间步骤可能会很困难。

标签: node.js axios content-type


【解决方案1】:

我认为您的评论是正确的,您需要先将其转换为文件。该通道不是问题,因为该文件将存储在托管机器人的任何位置。 Attachments Sample 实际上是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 });
});

我对@9​​87654326@ 部分不是很有信心,只是因为我无法针对您的 API 进行测试。我从here获得了大部分代码。

【讨论】:

  • 早上好。您的解决方案就像在本地运行的魅力一样。一旦托管在 Azure 上,我就遇到了问题。为它创建了一个新问题:stackoverflow.com/questions/58306146/…。如果您愿意,我将非常感谢您的帮助。
  • @Hessel 我们今天早上将您的新问题分配给了另一位支持工程师,他有更多的带宽来提供帮助。副手,我不确定问题可能是什么,除非它不喜欢文件保存的位置——部署的机器人使用非常不同的目录结构。
  • Tnx。我添加了一些日志记录。应该不难复制。
  • 只是评论这段代码sn-p,最后一行好像有错误:axios.post(url, forData, { headers }); 使用的变量似乎不正确,看起来应该是:@ 987654328@
猜你喜欢
  • 2020-10-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2019-06-13
  • 2019-03-19
  • 2019-10-31
  • 1970-01-01
相关资源
最近更新 更多