//创建http服务器
var server = http.createServer(function (req, res) {
//设置跨域
res.writeHead(200,{"Content-Type":"application/json;charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"X-Requested-With","Access-Control-Allow-Methods":"PUT,POST,GET,DELETE,OPTIONS"});
//接收到上传的文件,data是个buffer
req.on("data",function (data) {
var datastr=data.toString();//输出格式如附件:
//用正则表达式查看data的类型是否图片类型
var pattern=/filename=\".\.jpg\"|filename=\".\.jpeg\"|filename=\".\.png\"|filename=\".\.gif\"/i;
if(!pattern.test(datastr))//匹配不到图片格式提示选择图片上传
{
res.write([{result:"请选择图片上传"}]);
}
else
{
var patternstr=pattern.exec(datastr)[0];//匹配到filename="1.jpg"
var file_ext=(/jpg|jpeg|png|gif/i).exec(patternstr)[0];//从filename="1.jpg"中找出扩展名jpg
var curr_date=new Date();
//拼写上传成功后生成的图片文件名
var serv_file=curr_date.getFullYear().toString()+curr_date.getMonth().toString()+curr_date.getDate().toString()
+curr_date.getHours().toString()+curr_date.getMinutes().toString()+ curr_date.getSeconds().toString()
+curr_date.getMilliseconds().toString()+parseInt(Math.random()*10)+"."+file_ext;
//将buffer写入到图片文件中,上传成功
fs.writeFile(__dirname+"/"+serv_file,data,{flag:'a'},function (err) {
if(err)
{
console.log("图片上传失败"+err.toString());
}
else {
console.log("上传成功");**//生成了图片,但打开图片提示格式不正确。**
}
})
}
})
})