Log*_*gan 0 javascript json file-upload file-type node.js
我在我的节点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 "/"
Run Code Online (Sandbox Code Playgroud)
在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("/");
});
});
});
Run Code Online (Sandbox Code Playgroud)
form(action="", method="post", enctype="multipart/form-data")
input(type="file", name="displayImage")
input(type="submit", name="Upload")
Run Code Online (Sandbox Code Playgroud)
文件数据如下所示:
{ 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] } }
Run Code Online (Sandbox Code Playgroud)
我读过,对于一个JSON文件的正确MIME类型application/json然而,你可以看到它显示为application/octet-stream在req.files上面.这可以防止我从类型键中检查类型.检查上传的文件是否是Node JS中的有效JSON文件的最佳方法是什么?
尝试/捕获阅读?或者某种节点的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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以这样使用它:
var data = validateJSON('some potential json data');
if (data) {
// valid!
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3661 次 |
| 最近记录: |