formidable模块是一个Node.js模块,主要用于解析表单,支持get post请求参数,文件上传等。
可以通过 npm 下载,模块的引入还是用通过 require 。
npm i formidable
创建解析对象有四种方式,每种方式都可以使用并且没有区别
const formidable = require('formidable');
const form = formidable(options);
const { formidable } = require('formidable');
const form = formidable(options);
const { IncomingForm } = require('formidable');
const form = new IncomingForm(options);
const { Formidable } = require('formidable');
const form = new Formidable(options);;
在创建对象的时候,我们可以传入参数,option 是一个对象,下面我列举部分参数,option 对象中的每个属性都是非必须的。
在解析对象完成之后,我们就可以开始对表单进行解析了。具体语法是:form.parse(request, callback)
。
在使用parse
方法对表单进行解析时,解析对象经历了一系列过程,我们可以监听这些过程从而完成某些操作,这些过程我们可以理解为事件。
form.on('progress', (bytesReceived, bytesExpected) => {});
form.on('field', (name, value) => {});
form.on('fileBegin', (name, file) => {});
form.on('file', (name, file) => {});
form.on('error', (err) => {});
form.on('aborted', () => {});
form.on('end', () => {});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
label {
display: inline-block;
width: 70px;
margin-right: 5px;
text-align: right;
}
</style>
</head>
<body>
<form action="http://localhost:8989/index" enctype="multipart/form-data" method="POST">
<label for="#username">用户名:</label>
<input type="text" name="username" class="username" id="username">
<br />
<br />
<label for="#userpass">密码:</label>
<input type="password" name="userpass" id="userpass">
<br />
<br />
<label for="#userpass">照片:</label>
<input type="file" name="userimg" id="userage">
<br />
<br />
<label for="">性别:</label>
<label for=""> <input type="radio" name="usersex" class="usersex" checked value="男">男</label>
<label for=""> <input type="radio" name="usersex" class="usersex" value="女">女</label>
<br />
<button id="submit" type="submit">提交</button>
</form>
</body>
</html>
在使用js时必须保证已经将Node.js安装
const http = require('http');
const url = require('url');
const formidable = require('formidable');
let server = http.createServer((req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf8' });
let urlObj = url.parse(req.url, true);
let params = urlObj.query;
if (urlObj.path == "/index") {
const form = formidable();
if (req != null) {
form.parse(req, (err, fielads, files) => {
console.log("fielads", fielads);
console.log("files", files);
});
form.on('progress', (bytesReceived, bytesExpected) => {
console.log("收到的字节数" + bytesReceived);
console.log("预期字节数" + bytesExpected);
});
form.on('field', (name, value) => {
console.log(name + " = " + value);
});
form.on('fileBegin', (name, file) => {
console.log(name + " = ", file);
});
form.on('file', (name, file) => {
console.log(name + " = ", file);
});
form.on('end', () => {
console.log('结束解析');
});
}
}
res.end();
});
server.listen(8989);