1.安装Formidable
npm install formidable
Formidable中封装了传输文件需要使用的函数,方便易用。
2.前端
由于需要上传文件,注意设置 enctype="multipart/form-data"。
<!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>
</head>
<body>
<form action="http://127.0.0.1:3000/Resources" method="POST" enctype="multipart/form-data">
<p>
姓名:<input type="text" name = "name"/>
</p>
<p>
年龄:<input type="text" name = "age"/>
</p>
<p>
性别: <input type="radio" name = "sex" value="男"/>男
<input type="radio" name = "sex" value="女"/>女
</p>
<p>
图片:<input type="file" name = "image"/>
</p>
<p>
<input type="submit"/>
</p>
</form>
</body>
</html>
3.服务器端
服务器将客户上传的文件,保存到目录“./image”。
var http = require("http");
var url = require("url");
var querystring = require("querystring");
var formidable = require("formidable");
var server = http.createServer(function(req, res){
if(req.url == "/Resources" && req.method == "POST"){
var form = new formidable.IncomingForm();
form.uploadDir= "./image";
form.parse(req,function(err, fields, files){
if(err){
throw err;
}
console.log(fields); //文本
console.log(files); //文件
res.writeHead(200, {"Content-type":"text/plain"});
res.end("success");
});
}
});
server.listen(3000,"127.0.0.1");