如何使用jQuery在Node.js中验证JSON文件上传

时间:2019-07-18 11:05:56

标签: jquery node.js json file-upload

我正在读取上载的json文件数据,但我需要知道如何在上传时或上传后验证文件格式或错误的json格式数据。

app.post('/upload', function (req, res) {
  let sampleFile;
  if (Object.keys(req.files).length == 0) {
    res.status(400).send('No files were uploaded.');
    return;
  }
 // console.log('req.files >>>', req.files); // eslint-disable-line
  sampleFile = req.files.sampleFile;

  uploadPath = __dirname + '/uploads/' + sampleFile.name;

  sampleFile.mv(uploadPath, function (err) {
    if (err) {
      return res.status(500).send(err);
    }
   // console.log('file', uploadPath);
    let rawdata = fs.readFileSync(uploadPath);
    var student = JSON.parse(rawdata);
    emp = student.employee;
    //console.log(emp);
    res.render('upload.ejs',{emp:emp,uploadPath:uploadPath});
  });
});

我想在上传JSON数据后对其进行验证,并且可以识别JSON对象或JSON数组。

1 个答案:

答案 0 :(得分:1)

可能尝试更改以下代码:

let rawdata = fs.readFileSync(uploadPath);
var student = JSON.parse(rawdata);
emp = student.employee;

为:

    let rawdata = fs.readFileSync(uploadPath);
    let student;
    try {
        student = JSON.parse(rawdata);
        emp = student.employee;
    } catch(e) {
        // oops! invalid json found; take possible actions here
    }
    // continue your rest code here