如何测试上传的文件是否是Node JS中的json文件?

时间:2013-07-18 02:23:49

标签: javascript json node.js file-upload file-type

代码

我在我的节点app.coffee文件上有这个咖啡脚本代码来处理上传:

app.post "/import", (req, res) ->
  console.log req.files
  fs.readFile req.files.displayImage.path, (err, data) ->
    newPath = __dirname + "/uploads/" + req.files.displayImage.name
    fs.writeFile newPath, data, (err) ->
      throw err  if err
      res.redirect "/"

在JavaScript转换中,它显示如下:

app.post("/import", function(req, res) {
  console.log(req.files);
  return fs.readFile(req.files.displayImage.path, function(err, data) {
    var newPath;
    newPath = __dirname + "/uploads/" + req.files.displayImage.name;
    return fs.writeFile(newPath, data, function(err) {
      if (err) {
        throw err;
      }
      return res.redirect("/");
    });
  });
});

Jade格式的表格:

  form(action="", method="post", enctype="multipart/form-data")
    input(type="file", name="displayImage")
    input(type="submit", name="Upload")

来自控制台输出的req.files

文件数据如下所示:

{ displayImage: 
   { domain: null,
     _events: {},
     _maxListeners: 10,
     size: 1148,
     path: '/tmp/21096ac17833fa5e096f9e5c58a5ba08',
     name: 'package.json',
     type: 'application/octet-stream',
     hash: null,
     lastModifiedDate: Wed Jul 17 2013 22:04:58 GMT-0400 (EDT),
     _writeStream: 
      { _writableState: [Object],
        writable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        path: '/tmp/21096ac17833fa5e096f9e5c58a5ba08',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        pos: undefined,
        bytesWritten: 1148,
        closed: true,
        open: [Function],
        _write: [Function],
        destroy: [Function],
        close: [Function],
        destroySoon: [Function],
        pipe: [Function],
        write: [Function],
        end: [Function],
        setMaxListeners: [Function],
        emit: [Function],
        addListener: [Function],
        on: [Function],
        once: [Function],
        removeListener: [Function],
        removeAllListeners: [Function],
        listeners: [Function] },
     open: [Function],
     toJSON: [Function],
     write: [Function],
     end: [Function],
     setMaxListeners: [Function],
     emit: [Function],
     addListener: [Function],
     on: [Function],
     once: [Function],
     removeListener: [Function],
     removeAllListeners: [Function],
     listeners: [Function] } }

问题

我已经读过JSON文件的正确mime类型是application/json但是你可以看到它在application/octet-stream上面显示为req.files。这可以防止我从类型键中检查类型。检查上传的文件是否是Node JS中的有效JSON文件的最佳方法是什么?

试一试?或者某种节点的lint插件?对此有什么实用的方法?

1 个答案:

答案 0 :(得分:5)

您可以尝试在服务器端解析JSON:

function validateJSON(body) {
  try {
    var data = JSON.parse(body);
    // if came to here, then valid
    return data;
  } catch(e) {
    // failed to parse
    return null;
  }
}

然后你可以这样使用它:

var data = validateJSON('some potential json data');
if (data) {
  // valid!
}