node.js multer中间件

//第一步

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })
 var app = express()

//第二步

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file 
  // req.body will hold the text fields, if there were any 
})
 
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files 
  // req.body will contain the text fields, if there were any 
})

var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files 
  // 
  // e.g. 
  //  req.files['avatar'][0] -> File 
  //  req.files['gallery'] -> Array 
  // 
  // req.body will contain the text fields, if there were any 
})

//注释

1.文件上传有以下方法
muilter.single(‘file’), //适用于单文件上传
muilter.array(‘file’,num), //适用于多文件上传,num为最多上传个数,上传文件的数量可以小于num,
muilter.fields(fields), //适用于混合上传,比如A类文件1个,B类文件2个。官方API有详细说明。
2.file为上传字段名称,当使用form表单submit方式上传时,必须与表单上传的name属性保持一致。
表单记得加上  enctype=‘multipart/form-data’
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • //第一步 //第二步 //第三步(路由)
    飞鱼_JS阅读 446评论 1 0
  • 诗经全文及译文 《诗经》现存诗歌305篇,包括西周初年到春秋中叶共 500 余年的民歌和朝庙乐章,分为风、雅、颂三...
    观茉阅读 67,403评论 0 18
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 关于权限认证 权限认证是几乎任何系统都会存在的一个重要模块,但是往往权限认证又会是比较麻烦且复杂的模块。所以很多的...
    无聊数藏家阅读 8,163评论 0 8
  • 唐诗三百首详解(一 行宫 唐代:元稹(yuán zhěn) 寥落古行宫,宫花寂寞红。 白头宫女在,闲坐说玄宗。 译...
    汉唐雄风阅读 6,344评论 4 29