Node.js文件上传代码
varexpress=require('express');varapp=express();varbodyParser=require('body-parser');varfs=require("fs");varmulter=require('multer');variconv=require('iconv-lite');varfilelist=require('./filelist');varurlencodedParser=bodyParser.urlencoded({extended:false});app.use(multer({dest:'/tmp/'}).array('p_w_picpath'));app.use(express.static('public'));app.get('/',function(req,res){res.sendFile(__dirname+"/public/"+"h2.html");});app.get("/filelist",function(req,res){console.log("GETfilelist");vartxt=filelist.fileList('/books');res.writeHead(200,{'Content-Type':'text/html'});res.end(txt);})app.post("/process_post",urlencodedParser,function(req,res){vartxt="<!DOCTYPEhtml><html><head><title>这是一个测试页面</title><metacharset=\"utf-8\"></head><body>姓名:"+req.body.first_name+"<br/>年龄:"+req.body.age+"</body></html>";/*varresponse={"first_name":req.body.first_name,"age":req.body.age};*///console.log(response);res.writeHead(200,{'Content-Type':'text/html'});res.end(txt);});app.post('/file_upload',function(req,res){console.log(req.files[0]);//上传的文件信息vardes_file=__dirname+"/books/"+req.files[0].originalname;fs.readFile(req.files[0].path,function(err,data){fs.writeFile(des_file,data,function(err){if(err){console.log(err);}else{response={message:'Fileuploadedsuccessfully',filename:req.files[0].originalname};}console.log(response);vartxt="<!DOCTYPEhtml><html><head><title>这是一个测试页面</title><metacharset=\"utf-8\"></head><body>文件名:"+response.filename+"</body></html>";res.writeHead(200,{'Content-Type':'text/html'});res.end(txt);//res.end(iconv.encode(JSON.stringify(response.filename),'utf-8').toString());});});});varserver=app.listen(80,'localhost',function(){//如果不指定主机名'localhost',默认是IPv6varhost=server.address().address;varport=server.address().port;//console.log(host);console.log("访问地址:http://%s:%s",host,port);});//终端打印如下信息console.log('Serverrunningathttp://127.0.0.1:80/');
相关的H1.html文件内容:
<!DOCTYPEhtml><html><head><title>这是一个测试页面</title><metacharset="utf-8"></head><body><formid="tform"action="/process_post"method="post">姓名:<inputtype="text"name="first_name"><br/>年龄:<inputtype="text"name="age"><br/><inputtype="submit"value="提交"></form><br/><h4>文件上传:</h4>选择一个文件上传:<br/><formaction="/file_upload"method="post"enctype="multipart/form-data"><inputtype="file"name="p_w_picpath"size="50"/><br/><inputtype="submit"value="上传文件"/></form><br/><ahref="/filelist">文件浏览</a></body></html>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。