我们先创建一个Express项目,要使用文件上传的功能还需要下载multer模块。
npm install --save multer
下面我们在public文件夹下创建upload.html,内容如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>文件上传</title> 6 </head> 7 <body> 8 <h3>文件上传:</h3> 9 选择一个文件上传: <br /> 10 <form action="/upload" method="post" enctype="multipart/form-data"> 11 <input type="file" name="content" /> 12 <br /> 13 <input type="submit" value="上传文件" /> 14 </form> 15 </body> 16 </html>
然后再routes文件夹下创建upload.js,内容如下:
1 var fs = require('fs'); 2 var express = require('express'); 3 var multer = require('multer'); 4 5 var router = express.Router(); 6 var upload = multer({dest: 'upload_tmp/'}); 7 8 router.post('/', upload.any(), function(req, res, next) { 9 console.log(req.files[0]); // 上传的文件信息 10 11 var des_file = "./upload/" + req.files[0].originalname; 12 fs.readFile( req.files[0].path, function (err, data) { 13 fs.writeFile(des_file, data, function (err) { 14 if( err ){ 15 console.log( err ); 16 }else{ 17 response = { 18 message:'File uploaded successfully', 19 filename:req.files[0].originalname 20 }; 21 console.log( response ); 22 res.end( JSON.stringify( response ) ); 23 } 24 }); 25 }); 26 }); 27 28 module.exports = router;
最后在app.js里添加下面的代码:
var upload = require('./routes/upload'); app.use('/upload', upload);
执行,访问下面的地址即可:
http://localhost:3000/upload.html