/*var multer = require('multer');
var upload = multer({ storage: storage });
router.post('/', upload.single('file'), function(req, res, next) {
console.log('文件',req.body.file);
}*/
而使用formidable来解析
var formidable = require('formidable');
var form = new formidable.IncomingForm();
//缓存路径
form.uploadDir = "./temp";
form.keepExtensions = false;
//回调函数的files参数将会是一个file数组
form.multiples = true;
form.parse(req,function(err, fields, files){
//console.log('req',req);
//if(err) return next(err);
console.log(err,JSON.stringify(fields),files);
}
打印出的数据为 null '{"file":"[object HTMLInputElement]"}' {}
为什么会解析成files对象呢,求教大佬。
html:
<input type="file" />
<a href="javascript:void(0)">提交</a>
var Input = document.querySelector("input");
var A = document.querySelector('a');
A.onclick = function(){
// 创建一个FormData对象,用来组装一组用 XMLHttpRequest发送请求的键/值对
var fd = new FormData();
fd.enctype = "multipart/form-data";
fd.append('file', Input);
// Ajax
var request = new XMLHttpRequest();
request.open("POST", "/index",true);
//request.setRequestHeader("Content-type","application/form-data");
request.send(fd);
request.onreadystatechange = function(){
if(request.readyState === 4 & request.status === 200){
console.log("上传成功");
var response = JSON.parse(request.responseText);
console.log(response);
}
}
}