以圖片為例:
客戶端
html代碼
<input type='file' id='oImg'>
用FormDate對象包裹圖片
var oImg = document.getElementById('oImg');
var formDate = new FormData();
formDate.append('file',oImg.file[0] ) ;
ajax(formDate 田度,'post',url,callbacl); //封裝的ajax方法
node端
var chunks = [];
var size = 0;
req.on('data' , function(chunk)
{
console.log(chunk);
chunks.push(chunk);
size+=chunk.length;
});
req.on("end",function()
{
console.log(chunks);
var buffer = Buffer.concat(chunks , size);
if(!size){
res.writeHead(404);
res.end('');
return;
}
var rems = [];
//根據(jù)\r\n分離數(shù)據(jù)和報頭
for(var i=0;i<buffer.length;i++){
var v = buffer[i];
var v2 = buffer[i+1];
if(v==13 && v2==10){
rems.push(i);
}
}
//圖片信息
var picmsg_1 = buffer.slice(rems[0]+2,rems[1]).toString();
var filename = picmsg_1.match(/filename=".*"/g)[0].split('"')[1];
//圖片數(shù)據(jù)
var nbuf = buffer.slice(rems[3]+2,rems[rems.length-2]);
var path = './public/images/'+filename;
fs.writeFileSync(path , nbuf);
console.log("保存"+filename+"成功");
res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8'});
res.end('<div id="path">'+path+'</div>');
});