是的,我有点不知道如何正确输入标题... 我有一个 Node 服务器,它通过帖子形式接收图像。然后,我想将此图像发送到 Microsoft Vision 和相同的 Google 服务,以便从两者收集信息,执行一些操作,并将结果返回给访问我的服务器的用户。 我的问题是:如何发送实际数据?
这是关心该问题的实际代码:
const microsofComputerVision = require("microsoft-computer-vision");
module.exports = function(req, res)
{
var file;
if(req.files)
{
file = req.files.file;
// Everything went fine
microsofComputerVision.analyzeImage(
{
"Ocp-Apim-Subscription-Key": vision_key,
"content-type": "multipart/form-data",
"body": file.data.toString(),
"visual-features":"Tags, Faces",
"request-origin":"westcentralus"
}).then((result) =>
{
console.log("A");
res.write(result);
res.end();
}).catch((err)=>
{
console.log(err);
res.writeHead(400, {'Content-Type': 'application/json'});
res.write(JSON.stringify({error: "The request must contain an image"}));
res.end();
});
}
else
{
res.writeHead(400, {'Content-Type': 'application/octet-stream'});
res.write(JSON.stringify({error: "The request must contain an image"}));
res.end();
}
}
如果我不调用“analyzeImage”,而是执行以下操作
res.set('Content-Type', 'image/jpg')
res.send(file.data);
res.end();
浏览器正确渲染图像,这让我认为“file.data”包含实际文件(认为它是缓冲区类型)。 但显然微软不同意这一点,因为当我向计算机视觉发送请求时,我得到以下响应: “无效图像格式”
我找到的唯一例子是 here ,该示例中使用的“数据”来自文件系统读取,而不是直接来自请求。但是保存文件以加载它,然后将其删除给我看起来是一个可怕的解决方法,所以我想知道以什么形式以及如何处理我必须正确发送它以供 API 调用的"file"。
<小时/>编辑:如果我使用 file.data (我认为这是最正确的,因为它将发送原始图像作为正文),我会收到一个错误,表明我必须使用字符串或缓冲区作为内容。显然,file.data 并不是“body”所需要的缓冲区,O.o 我并不诚实地理解。
<小时/>已解决,错误相当愚蠢。在“then”部分,res.write(result) 不接受结果作为参数。当我实际使用corret请求(file.data,它是一个缓冲区)时发生这种情况。每次我尝试在 file.data 上使用 toString() 时都会发生其他错误,在这种情况下请求未被接受。
最佳答案
已解决,请求请求缓冲区,而file.data确实是缓冲区。以任何可能的方式检查 file.data 类型后,我开始寻找其他问题。这个错误要容易得多,请原谅我的愚蠢,愚蠢到不明显。结果是一个 json,而 res.write 不接受 json 作为参数。
关于node.js - 发送图像作为请求正文,图像通过外部请求接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49078912/