发送图像作为请求的正文,从外部请求接收的图像

问题描述 投票:1回答:2

是的,我有点不知道如何键入标题...我有一个节点服务器,通过帖子形式重现图像。然后,我想将此图像发送到Microsoft愿景和相同的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”包含实际文件(认为它是缓冲区类型)。但显然微软并不同意这一点,因为当我向计算机视觉发送请求时,我得到以下响应:“InvalidImageFormat”

我发现的唯一例子是here,该示例中使用的“数据”来自文件系统读取,而不是来自请求。但保存文件加载它,然后将其删除给我看起来像一个可怕的解决方法,所以我想知道以什么形式,我应该如何工作的“文件”,我必须正确发送它的API呼叫。


编辑:如果我使用file.data(我认为它是最正确的,因为它将原始图像作为正文发送)我得到一个错误,说我必须使用字符串或缓冲区作为内容。显然,file.data不是“身体”需要O.o的缓冲区。我不是老老实实地理解。


解决了,这个错误非常愚蠢。在“then”部分,res.write(result)不接受结果作为参数。当我实际使用了corret请求(file.data是一个缓冲区)时,就发生了这种情况。每次我尝试在file.data上使用toString()时都会发生其他错误,在这种情况下请求不被接受。

node.js api express raw-data
2个回答
1
投票

解决了,请求缓冲区,file.data确实是一个缓冲区。在以任何可能的方式查找file.data类型后,我开始寻找其他问题。错误更容易,原谅我是愚蠢的,太愚蠢而不明显。结果是一个json,res.write不接受json作为参数。


0
投票

这就是我使用亚马逊识别图像分类器的方式,我知道它与您使用的服务不同 - 希望这对您有所帮助:

const imagePath = `./bat.jpg`;
const bitmap = fs.readFileSync(imagePath);
const params = {
            Image: { Bytes: bitmap },
            MaxLabels: 10,
            MinConfidence: 50.0
        };
route.post('/', upload.single('image'), (req, res) => {
    let params = getImage();
    rekognition.detectLabels(params, function(err, data) {
        if (err) {
            console.log('error');
        }else {
            console.log(data);
            res.json(data);
        }
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.