index.htm:
<html> <head> <title>文件上传表单</title> </head> <body> <h3>文件上传:</h3> 选择一个文件上传: <br /> <!-- post请求,修改数据 --> <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>
server.js:
var express = require('express'); var app = express(); var fs = require("fs"); var bodyParser = require('body-parser'); //multer是express官方推荐的文件上传中间件 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.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" );//输出静态文件 }) 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 };//设置response属性 } console.log( response );//服务端提示 res.end( JSON.stringify( response ) );//输出到浏览器 }); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("应用实例,访问地址为 http://%s:%s", host, port) })
上传的东西:
服务端:
浏览器客户端:
乱码,没设置转码的问题