const formidable = require('formidable');
const path = require('path');
module.exports = (req, res) => {
// 1.创建表单解析对象
const form = new formidable.IncomingForm();
// 2.配置上传文件的存放位置
form.uploadDir = path.join(__dirname, '../', '../', 'public', 'uploads');
// 3.保留上传文件的后缀
form.keepExtensions = true;
// 4.解析表单
form.parse(req, (err, fields, files) => {
// 1.err错误对象 如果表单解析失败 err里面存储错误信息 如果表单解析成功 err将会是null
// 2.fields 对象类型 保存普通表单数据
// 3.files 对象类型 保存了和上传文件相关的数据
res.send(fields);
})
console.log(111);
}
浏览器一直在打圈圈,没有收到任何响应,但终端输出了111,说明程序运行时直接跳过了parse的部分。
查了一圈发现是,需要提交的form,要加一个属性enctype的属性。
<form action='/article' method='post' enctype="multipart/form-data">
<input type="file">
</form>
enctype指定表单的数据编码类型。表单的默认类型为 application/x-www-form-urlencoded,如 name=zhangsan&age=20。如果表单中有需要上传的文件(<input type="file">
),需要将表单数据类型编码为2进制类型,使用 multipart/form-data。