express + node.js 简单实现多文件上传功能

upload.js:

var express = require('express');
var router = express.Router();
var fs = require("fs");

/* 上传*/
router.post('/file_upload', function (req, res) {
   console.log(req.files);  // 上传的文件信息
   console.log(req.body.test);for(let i=0;i<req.files.length;i++){
      fs.readFile( req.files[i].path, function (err, data) {
            let des_file = "./public"+"/" + req.files[i].originalname;//存放路径
            fs.writeFile(des_file, data, function (err) {
            if( err ){
                  console.log( err );
            }else{
                  response= {
                      message:'File uploaded successfully', 
                      filename:req.files[i].originalname
                  }
              }
              console.log( data );
              console.log(des_file);
              res.end( JSON.stringify( response ) );
          });
      });
   }
   res.end( JSON.stringify( response ) );
})
module.exports = router;

测试用的前端页面:

<h3>文件上传:</h3>
选择一个文件上传: <br />
<form action="http://127.0.0.1:3000/file_upload" method="post" enctype="multipart/form-data">
<input name="test" type="text">
<input type="file" name="image" size="50" multiple="multiple"/>
<br />
<input type="submit" value="上传文件" />
</form>

 

posted @ 2017-07-21 15:29  pfr  阅读(957)  评论(0编辑  收藏  举报