0

I am reading uploaded json files data but I need to know how can we validate file format or wrong json format data while uploading or after uploading it.

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});
  });
});

I wants to validate json data after uploading it and can I identify JSON objects or json array.

1 Answer 1

1

Possibly trying changing your following code:

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

as:

    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
Sign up to request clarification or add additional context in comments.

2 Comments

ok Can i check uploaded data contains objects only or objects array ?
you can do Array.isArray(PASS_VAR_HERE) if it returns true it is array else it is not. Please mark answer accepted & upvote, if it helped you in your original question, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.