login.html 檔案
<html> <body> <form action="/login" method="POST"> First Name: <input type="text" name="first_name"> <br> Last Name: <input type="text" name="last_name"> <input type="submit" value="Submit"> </form> </body> </html>
node 檔案
var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/', function (req, res) { res.send('Hello World'); }) app.get('/login.html', function (req, res) { res.sendFile( __dirname + "/" + "login.html" ); }) app.post('/login', function (req, res) { // 輸出 JSON 格式 var response = { "first_name":req.query.first_name, "last_name":req.query.last_name }; console.log(response); res.end(JSON.stringify(response)); }) var server = app.listen(8080, function () { var host = server.address().address var port = server.address().port console.log("應用實例,訪問地址為 http://%s:%s", host, port) })
index.html 檔案
<html> <head> <title>檔案上傳表單</title> </head> <body> <h3>檔案上傳:</h3> 請選擇一個檔案上傳: <br /> <form action="/file_upload" method="post" enctype="multipart/form-data"> <input type="file" name="image" size="50" /> <br /> <input type="submit" value="上傳檔案" /> </form> </body> </html>
var express = require('express'); var app = express(); var fs = require("fs"); var bodyParser = require('body-parser'); var multer = require('multer'); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(multer({ dest: '/tmp/'}).array('image')); app.get('/index.html', function (req, res) { res.sendFile( __dirname + "/" + "index.html" ); }) app.post('/file_upload', function (req, res) { console.log(req.files[0]); // 上傳的檔案信息 var des_file = __dirname + "/" + 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 ); res.end( JSON.stringify( response ) ); }); }); }) var server = app.listen(8080, function () { var host = server.address().address var port = server.address().port console.log("應用實例,訪問地址為 http://%s:%s", host, port) })