簡體   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