代码
我的 Node app.coffee 文件中有这个 CoffeeScript 代码来处理上传:
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
,但是正如您所看到的,它在上面的 req.files
中显示为 application/octet-stream
。这使我无法从类型键检查类型。在 Node JS 中检查上传的文件是否是有效的 JSON 文件的最佳方法是什么?
尝试/捕获阅读?或者某种 Node 的 lint 插件?对此的实用方法是什么?
最佳答案
您可以尝试在服务器端解析 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!
}
关于javascript - Node JS 如何测试上传的文件是否是json文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17713485/