繁体   English   中英

强大/NodeJS HTTP 服务器 JPG 保存

[英]Formidable/NodeJS HTTP Server JPG save

Stackoverflow JS 天才的!

我当前的项目有一个问题,它使用节点的 HTTP createServer,使用 Formidable 来解析正文数据。

请参阅下面的代码。 (http-listener.js)

var listenport = 7200;

const server = http.createServer((req, res) => {

  // Set vars ready
  var data = '';
  var plateImg = '';
  var overview1 = '';
  var overview2 = '';

  new formidable.IncomingForm().parse(req)
  // I originally thought it was sent in files, but it isnt, it's fields.
  .on('file', function(name, file) {
    console.log('Got file:', name);
  })
  // This is the correct procedure for my issue.
  .on('field', function(name, field) {
    console.log('Got a field:', name);
    if(name.toLowerCase() === "anpr.xml")
    {
      // DO PARSE INTO JSON! This works, all is well.
      xml2js.parseString(field, {explicitArray:false, ignoreAttrs:true}, function (err, result)
      {
        if(err)
        {
          alert('Parse: '+err);
        }
        // Console log parsed json data.
        console.log("Read: "+result.EventNotificationAlert.ANPR.licensePlate);
        console.log(result);
        data = result;
      });
    }
    if(name.toLowerCase() === "licenseplatepicture.jpg")
    {
      plateImg = field
      // This doesnt work?
      // I need to store these fields as an image. ? Is this possible with it being sent as a field and not as a file upload.
      // This is the only option I have as I can't control the client sending this data (It's a camera)
      fs.writeFile(config.App.ImageDir+'/Plate.jpg', plateImg, function(err) {
        if(err)console.log(err);
      });
    }
    if(name.toLowerCase() === "detectionpicture.jpg")
    {
      if(overview1 == '')
      {
        overview1 = field;
      }
      else if(overview2 == '')
      {
        overview2 = field;
      }
      else
      {
        // do nothing else.
        console.log("Couldn't send images to variable.");
      }
    }
  })
  .on('error', function(err) {
    alert(err);
  })
  .on('end', function() {
    // Once finished, send to ANPR data to function to handle data and insert to database. WORKS
    // Call anpr function.
    ANPR_ListenData(data, plateImg, overview1, overview2, function(result) {
      if(result.Status > 0)
      {
        console.log("Accepted by: "+result.Example);
        // reset var
        data = '';
        plateImg = '';
        overview1 = '';
        overview2 = '';
        res.writeHead(200, {'content-type':'text/html'});
        res.end();
      }
    });
  });
});

server.listen(listenport, () => {
  console.log('ANPR Server listening on port: ' + listenport);
});

基本上是在字段中发送的图像: licenseplatepicture.jpg 等我想将它们直接存储到我的应用程序图像目录中。

不幸的是,由于它是网络摄像机,我无法控制如何将块发送到该服务器,我只需要编写一个程序。

完整的请求块非常大,所以我将文件上传到 OneDrive 以供您查看和理解请求。

对此的任何帮助将不胜感激。 我已经尝试了所有我能想到的东西,但文件保存不可读:(。除了我已经做过和尝试过的事情之外,我不知道还能去哪里看或还能尝试什么。

请求文本文件: https://1drv.ms/t/s?AqAIyFoqrBTO6hTwCimcHDHODqEi?e=pxJY00

瑞安。

我通过使用 Busboy package 而不是 Formidable 解决了这个问题。

这就是我的 http 监听器在使用 Busboy 时的样子。

var inspect = util.inspect;

var Busboy = require('busboy');

http.createServer(function(req, res) {
  if (req.method === 'POST') {
    //vars
    var ref = Math.random().toString(36).substring(5) + Math.random().toString(36).substring(2, 15);;
    var xml = '';
    var parseXml = '';
    var over1, over2 = '';
    var i = 0;

    var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
      if(filename.toLowerCase() === "licenseplatepicture.jpg")
      {
        var saveTo = config.App.ImageDir+"/"+ref+"_Plate.jpg";
        if (!fs.existsSync(saveTo)) {
          //file exists
          file.pipe(fs.createWriteStream(saveTo));
        }
      }
      if(filename.toLowerCase() === "detectionpicture.jpg")
      {
        i++;
        var saveTo = config.App.ImageDir+"/"+ref+"_Front_"+i+".jpg";
        if (!fs.existsSync(saveTo)) {
          //file exists
          file.pipe(fs.createWriteStream(saveTo));
        }
      }
      file.on('data', function(data) {
        if(filename.toLowerCase() === "anpr.xml")
        {
          xml += data;
        }
        console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
      });
      file.on('end', function() {
        console.log('File [' + fieldname + '] Finished');
      });
    });
    busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
      console.log('Field [' + fieldname + ']: value: ' + inspect(val));
      // No fields according to busboy
    });
    busboy.on('finish', function() {
      // DO PARSE INTO JSON! This works, all is well.
      xml2js.parseString(xml, {explicitArray:false, ignoreAttrs:true}, function (err, result)
      {
        if(err)
        {
          alert('Parse: '+err);
        }
        // Set parsed var
        parseXml = result;
      });
      var images = '';
      if(i = 2)
      {
        images = `{"Plate":"${ref}_Plate.jpg", "Front":"${ref}_Front_1.jpg", "Overview":"${ref}_Front_2.jpg"}`;
      } else {
        images = `{"Plate":"${ref}_Plate.jpg", "Front":"${ref}_Front_1.jpg", "Overview":"null"}`;
      }
      // Once parsed, send on to ANPR listen function.
      ANPR_ListenData(ref, parseXml, images, function(result) {
        if(result.Status == 1)
        {
          console.log('Data transfered for: '+parseXml.EventNotificationAlert.ANPR.licensePlate);
          console.log('Accepted Camera: '+result.Example);
          res.writeHead(200, { Connection: 'close', Location: '/' });
          res.end();
        }
      });
    });
    req.pipe(busboy);
  }
}).listen(7200, function() {
  console.log('Listening for requests');
});

希望这对将来的其他人有所帮助。 肯定给我浪费了很多时间。

Busboy 是更好的 package,当我更多地阅读它时,它对我试图实现的目标更有意义。

瑞恩:)。 一切顺利。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM