我使用 TypeScript 编写了一个 Azure 函数来处理一些二进制数据。虽然我的第一种方法从文件系统读取二进制数据成功了,但通过
POST
请求将二进制数据作为正文传递却失败了。
curl -v \
-X POST \
--data-binary @resources/example.pdf \
$function_url
# > Content-Length: 2505058
我使用以下代码从请求正文中读取数据。
const dataFromFs = new Uint8Array(readFileSync('resources/example.pdf'));
context.log(`Read PDF file from filesystem with length ${dataFromFs.length}`);
// Read PDF file from filesystem with length 2505058
const dataFromReq = new Uint8Array(Buffer.from(req.body));
context.log(`Read PDF file from request body with length ${dataFromReq.length}`);
// Read PDF file from request body with length 4365547
由于读取请求体的内容长度与HTTP请求和文件系统解决方案不同,我猜测问题是由
new Uint8Array(Buffer.from(req.body))
引起的。
有什么建议吗?
GitHub 问题 Azure Functions(节点)无法正确处理二进制数据 描述了该问题并建议将
Content-Type
标头设置为 application/octet-stream
。
curl -v \
-X POST \
-H 'Content-Type: application/octet-stream'
--data-binary @resources/example.pdf \
$function_url
# > Content-Length: 2505058
Azure 函数使用
Buffer.from(req.body, 'binary')
读取请求正文。
const dataFromReq = new Uint8Array(Buffer.from(req.body, 'binary'));
context.log(`Read PDF file from request body with length ${dataFromReq.length}`);
// Read PDF file from request body with length 2505058
根据@sschmeck引用的问题,您现在可以在
req.bufferBody
中找到缓冲区。