首先利用http创建一个server,监听到8080端口,之后我们可以打印req.headers查看headers的内容,post的数据
格式一般为:
------WebKitFormBoundaryLIXOJt36aIHyhrvq
Content-Disposition: form-data; name="username"
1
------WebKitFormBoundaryLIXOJt36aIHyhrvq
Content-Disposition: form-data; name="password"
1
------WebKitFormBoundaryLIXOJt36aIHyhrvq
Content-Disposition: form-data; name="f1"; filename="aaa.txt"
Content-Type: text/plain
abcd
1234
------WebKitFormBoundaryLIXOJt36aIHyhrvq--
利用该格式处理出我们需要的数据,都是一些字符以及二进制操作。
server.js
const http=require('http');
const util=require('buffer_util');
const fs=require('fs');
http.createServer((req, res)=>{
let arr=[];
console.log(req.headers);
let boundary='--'+req.headers['content-type'].split('; ')[1].split('=')[1];
console.log(boundary);
req.on('data',buffer=>{
arr.push(buffer);
});
req.on('end',()=>{
let buffer=Buffer.concat(arr);
console.log('最初'+buffer);
let arr2=util.bufferSplit(buffer,boundary);
arr2.pop();
arr2.shift();
arr2.forEach(buffer=>{
console.log('原始'+buffer.toString());
buffer=buffer.slice(2,buffer.length-2);
let n=buffer.indexOf('\r\n\r\n');
let info=buffer.slice(0,n).toString();
let data2=buffer.slice(n+4,buffer.length);
// console.log('--'+info);
// console.log('-'+data2);
if(info.indexOf('\r\n')!=-1){//文件信息
let res2 = info.split('\r\n')[0].split('; ');
let name = res2[1].split('=')[1];
let filename = res2[2].split('=')[1];
name=name.substring(1,name.length-1);
filename=filename.substring(1,filename.length-1);
console.log('&&&&&'+name, filename+'&&&&&&&&');
fs.writeFile(`upload/${filename}`,data2,err=>{
if(err){
console.log(err);
}else {
console.log('上传成功');
}
})
}else{
let name=info.split('; ')[1].split('=')[1];
name=name.substring(1,name.length-1);
console.log(name);
}
console.log('**'+data2.toString()+'**');
})
});
}).listen(8080);
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="file" name="f1">
<input type="submit" value="提交">
</form>
</body>
</html>
利用multiparty库解决上面的问题
const http=requrie('http');
const multiparty=requrie('multiparty');
http.createServer((req,res)=>{
let form = new multiparty.Form({
uploadDir: './upload'
});
form.parse(req);
form.on('field',(name,value)=>{
console.log('字段',name,value);
});
form.on('file',(name,file)=>{
console.log('文件',name,file);
});
form.on('close',()=>{
console.log('表单解析完成');
})
}).listen(8080);