Node.js文件上传代码

2023-06-07,,

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require("fs");
var multer  = require('multer');
var iconv = require('iconv-lite');
var filelist = require('./filelist');

var urlencodedParser = 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("GET filelist");

    var txt = filelist.fileList('/books');
            
    res.writeHead(200,{'Content-Type':'text/html'});
    res.end(txt);
})

app.post("/process_post",urlencodedParser,function(req,res){
	var txt = "<!DOCTYPE html><html><head><title>这是一个测试页面</title><meta charset=\"utf-8\"></head><body>姓名:"+
		req.body.first_name+"<br />年龄:"+
		req.body.age+"</body></html>";
	/*var response={
		"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]);  // 上传的文件信息
 
   var des_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:'File uploaded successfully', 
                   filename:req.files[0].originalname
              };
          }
          console.log( response );
          
          var txt = "<!DOCTYPE html><html><head><title>这是一个测试页面</title><meta charset=\"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());
       });
   });
});

var server = app.listen(80,'localhost',function(){  //如果不指定主机名'localhost',默认是 IPv6
	var host = server.address().address;
    var port = server.address().port;
    //console.log(host);

	console.log("访问地址:http://%s:%s",host,port);
});

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:80/');

相关的H1.html文件内容:

<!DOCTYPE html>
<html>
<head>
<title>这是一个测试页面</title>
<meta charset="utf-8">
</head>
<body>
<form  id="tform" action="/process_post" method="post">
	姓名:<input type="text" name="first_name"><br />
	年龄:<input type="text" name="age"><br />
	<input type="submit" value="提交">
</form>
<br />
<h4>文件上传:</h4>
选择一个文件上传: <br />
<form action="/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="p_w_picpath" size="50" />
<br />
<input type="submit" value="上传文件" />
</form>
<br />
<a href="/filelist">文件浏览</a>
</body>
</html>