node - post - 上传图片
html代码:
1 <!DOCTYPE html>
2 <html lang="en">
3
4 <head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
8 <title>Document</title>
9 </head>
10
11 <body>
12 <form action="http://127.0.0.1/dopost" enctype="multipart/form-data" method="POST">
13 姓名:<input type="text" name="name"> 性别:
14 <input type="radio" name="gender" value="男">男<input type="radio" name="gender" value="女">女 年龄:
15 <input type="number" name="age"> 图片:
16 <input type="file" name="img">
17 <input type="submit" value="提交">
18 </form>
19 </body>
20
21 </html>
js代码
1 let http = require('http'); 2 let formidable = require('formidable'); 3 let util = require('util'); 4 5 6 //创建服务器 7 let server = http.createServer(function (req, res) { 8 //如果你的访问地址是这个,并且请求类型是post 9 if (req.url == '/dopost' && req.method.toLowerCase() == 'post') { 10 let form = new formidable.IncomingForm(); 11 //设置文件上传存放地址 12 form.uploadDir = './uploads'; 13 //执行里面的回调函数的时候,表单已经全部接收完毕了。 14 form.parse(req, function (err, fields, files) { 15 if (err) throw err; 16 console.log('上传文件路径:',files.img.path,'上传文件名:',files.img.name); 17 // console.log(util.inspect({ fields: fields, files: files })); 18 //所有的文本域、单选框,都在fields存放; 19 //所有的文件域,files 20 res.writeHead(200, { 'content-type': 'text/plain' }); 21 22 res.end('success!~~~'); 23 }); 24 } 25 }); 26 27 server.listen(80, '127.0.0.1');