formidable模块解析上传文件

nodejs有很多上传文件插件,formidable可以直接解析nodejs的原生请求对象,即IncomingMessage类的对象,很多框架都是使用的nodejs原生的请求对象

使用方式

 

var formidable = require('formidable'),
    http = require('http'),
    util = require('util');

http.createServer(function(req, res) {
    //创建表单上传
    var form = new formidable.IncomingForm();
    //设置编辑
    form.encoding = 'utf-8';
    console.log(req)
    form.parse(req, function(err, fields, files) {
         console.dir(fields)
         console.dir(files)
    });
    res.end('hello world!');
}).listen(8080,'localhost');

其中fields为除了文件之外的字段的对象,files为文件字段对象,输出为

 

 

{ name: '吃饭的艺术', age: '1111' }
{ file1: 
   File {
     ...
     size: 54,
     path: 'C:\\Users\\xxx\\AppData\\Local\\Temp\\upload_0d338030a0cd1a49b90cc5ac53fb7c72',
     name: 'dota.txt',
     type: 'text/plain',
     hash: null,
     lastModifiedDate: 2017-12-30T15:43:46.934Z,
     _writeStream: 
      WriteStream {
        ...
        path: 'C:\\Users\\xxx\\AppData\\Local\\Temp\\upload_0d338030a0cd1a49b90cc5ac53fb7c72',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        autoClose: true,
        pos: undefined,
        bytesWritten: 54,
        closed: true } },
  'file2': 
   File {
     ...
     size: 18,
     path: 'C:\\Users\\xxx\\AppData\\Local\\Temp\\upload_ef9741fc431f1f0bf193b013be436f33',
     name: 'lol.txt',
     type: 'text/plain',
     hash: null,
     lastModifiedDate: 2017-12-30T15:43:46.935Z,
     _writeStream: 
      WriteStream {
        ...
        path: 'C:\\Users\\xxx\\AppData\\Local\\Temp\\upload_ef9741fc431f1f0bf193b013be436f33',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        autoClose: true,
        pos: undefined,
        bytesWritten: 18,
        closed: true } } }

可见文件对象中属性名为文件字段名,属性值为formidable中的File对象

 

File对象主要参数为

size:文件字节

path:文件保存路径,可以在form上设置上传目录,未设置的话会使用系统默认临时目录

name:文件名

type:文件MIME

_writeStream:一个已经关闭的可写流,即文件写入磁盘时的流

可以使用fs.readFileSync()方法读取path,获取文件字节数组
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值