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,获取文件字节数组