nodejs 实现文件上传

2018-06-13  本文已影响0人  希硕

前端页面结构

<form method="post" action="http://localhost:8080/uploadReport" enctype="multipart/form-data">
       <input type="file" name="filename"/> //
       <input type="submit" value="提交"/>
   </form>
TIM截图20180613154019.png

node 服务端

需用到connect-multiparty 模块

npm install connect-multiparty --save

完整代码:

var express = require('express');
var router = express.Router();
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
router.route('/uploadReport').post(multipartMiddleware,function(req, res) {
   try{
     console.log('/uploadReport',req.files);
      let originalFilename = req.files.filename.originalFilename;//
      let extName = "";
      //判断文件是否具有扩展名
      if(originalFilename.lastIndexOf(".") != -1){
         extName = originalFilename.slice(originalFilename.lastIndexOf("."));//获取文件扩展名
      }
      let fileName =Math.round(Math.random()*10000) + extName;//文件重命名
      var source = fs.createReadStream(req.files.filename.path);//读取临时文件流
      var output = path.join(__dirname,"../public/",fileName);//

      var dest = fs.createWriteStream(output);
      source.pipe(dest);
      source.on('end', function() {
  
         fs.unlinkSync(req.files.filename.path);
         res.send("HTTP_SUCCESS:");
      }); 
      source.on('error', function(err) {
      console.log('文件复制出错',err)
      });
   }catch(e){
      console.log('uploadReport',e)
   }
})

控制台打印一下req.files:

{ 
           filename:
           { 
                fieldName: 'filename', // 文件名
                originalFilename: 'f739f32795f756ba4f1739fffd61a372.jpg',//原始文件名
                path:
                   'C:\\Users\\dell\\AppData\\Local\\Temp\\mOqRkZgc8gpjDpXDe6Xn_x8Q.jpg',
                headers:
                    { 
                        'content-disposition':'form-data; name="filename"; filename="f739f32795f756ba4f1739fffd61a372.jpg"',
                        'content-type': 'image/jpeg'
                    },
                size: 20562,//文件大小
                name: 'f739f32795f756ba4f1739fffd61a372.jpg',
                type: 'image/jpeg' //文件类型
           } 
       }
上一篇下一篇

猜你喜欢

热点阅读