【问题标题】:How to return base64 image from Azure Function as binary data如何从 Azure Function 返回 base64 图像作为二进制数据
【发布时间】:2021-10-01 00:46:34
【问题描述】:

Azure 函数 HTTP 绑定从 Azure Blob 存储读取图像作为 Base64 字符串。

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQTEhIUEhIUFBUV…K9rk8hCAEkjFMUYiEAI+nHIpsQh0AkisDYRTOiCAbWVtgCtI6IlkHh7LDTQXLH0EIQBj//2Q==

它使用一个新的缓冲区来转换它:

const buf = new Buffer(pictureObj.data.split(",")[1], "base64");

然后它以这种方式返回这个缓冲区:

context.bindings.res = {
    "status": 200,
    "headers": {
        "Content-Type": type || "image/jpeg"
     },
     "body": new Uint8Array(buf)
};

不幸的是,这不起作用。设置“isRaw”也不起作用以及返回缓冲区(buf)本身。错误为 406(不可接受)且正文为空。

问题是:如何通过 HTTP 输出绑定将 base64 作为二进制图像返回?

此外,再添加一个标头(例如 Content-Length)失败并出现以下错误:

info: Worker.Node.2a68d094-3858-406b-a0c5-a81497b3436b[0]
  Worker 2a68d094-3858-406b-a0c5-a81497b3436b malformed message invocationResponse.outputData.data.http.headers: string{k:string} expected
[03/12/2017 02:44:32] A ScriptHost error has occurred
[03/12/2017 02:44:32] Error: Choose either to return a promise or call 'done'.  Do not use both in your script.
[03/12/2017 02:44:32] Error: Choose either to return a promise or call 'done'.  Do not use both in your script.

【问题讨论】:

  • 用 application/octet-stream content-type 进行了实验,结果是一样的。不设置 content-type 将缓冲区返回为 base64 字符串。

标签: node.js azure azure-functions


【解决方案1】:

如果您使用的是 Azure 函数测试版,这应该可以工作:

context.res.setHeader("Content-Type", "image/jpeg")
context.res.raw(new Uint8Array(buf))

此外,当使用 raw 或 send 时,无需调用 context.done,因为它是隐式调用的。

【讨论】:

  • 太棒了。这适用于 beta 中部署的功能,但不适用于本地模拟器。这可能是因为我还没有想出如何在本地模拟器上启用 beta 功能。
  • 确保 npm install -g azure-functions-core-tools@core 最新版本是 2.0.1-beta.22,应该与 Azure Functions beta 匹配
  • 这在非测试版中似乎不起作用,还有其他方法吗?
  • 您可以简单地尝试将主体设置为 Buffer 元素: context.res.setHeader("Content-Type", "application/octet-stream"); context.res.body = binaryFile;
  • 这个错误对我不起作用:异常:TypeError:context.res.setHeader is not a function
【解决方案2】:

多年来,context.res 对象的语法有changed。这是我最近使用 TypeScript Azure Function 实现的方法。

    const base64Image: string = 'data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQTEhIUEhIUFBUV…K9rk8hCAEkjFMUYiEAI+nHIpsQh0AkisDYRTOiCAbWVtgCtI6IlkHh7LDTQXLH0EIQBj//2Q==';
const buffer: Buffer = new Buffer(base64Image.split(",")[1], "base64");

context.res = {
    headers: {
        "Content-Type": "image/png"
    },
    isRaw: true,
    // status: 200, /* Defaults to 200 */
    body: new Uint8Array(buffer)
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多