nodejs - multer模块教程,使用multer进行附件上传

介绍

multer是Nodejs中用于处理文件上传 multipart/form-data数据的中间件,用于处理任何表单提交数据(包含非multipart/form-data类型的表单); 
multer 在request对象中加入了body和file或files属性,body属性包含了form中的文本内容,file或files包含了form 中的附件数据
  1. var express = require('express')  
  2. var multer  = require('multer')  
  3. var upload = multer({ dest: 'uploads/' })  
  4.    
  5. var app = express()  
  6.    
  7. app.post('/profile', upload.single('avatar'), function (req, res, next) {  
  8.   // req.file is the `avatar` file   
  9.   // req.body will hold the text fields, if there were any   
  10. })  
  11.    
  12. app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {  
  13.   // req.files is array of `photos` files   
  14.   // req.body will contain the text fields, if there were any   
  15. })  
  16.    
  17. var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])  
  18. app.post('/cool-profile', cpUpload, function (req, res, next) {  
  19.   // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files   
  20.   //   
  21.   // e.g.   
  22.   //  req.files['avatar'][0] -> File   
  23.   //  req.files['gallery'] -> Array   
  24.   //   
  25.   // req.body will contain the text fields, if there were any   
  26. })  
var upload = multer({ dest: 'uploads/' })参数说明
key description
dest or storage Where to store the files
fileFilter Function to control which files are accepted
limits Limits of the uploaded data
upload方法说明
.single(fieldname)

Accept a single file with the name fieldname. The single file will be stored in req.file.

接收一个叫做<fieldname>名字的附件,该附件将被保存到req.file属性中

.array(fieldname[, maxCount])

Accept an array of files, all with the name fieldname. Optionally error out if more than maxCountfiles are uploaded. The array of files will be stored in req.files.

接收一个所有附件的名字是<fieldname>的附件数组,如果附件的数量大于<maxCountfiles>则抛出异常。文件数组将被储存到req.files属性中。

.fields(fields)

Accept a mix of files, specified by fields. An object with arrays of files will be stored inreq.files.

fields should be an array of objects with name and optionally a maxCount. Example:

接收所有名称的附件,附件将被保存到req.files属性中(是一个对象数组),配置参数如下

   
   
[
  { name: 'avatar', maxCount: 1 },
  { name: 'gallery', maxCount: 8 }
]
.any()

Accepts all files that comes over the wire. An array of files will be stored in req.files.

接收所有提交的数据,保存到req.files属性中

storage

DiskStorage

The disk storage engine gives you full control on storing files to disk.

你可以使用硬盘存储模式设置在哪里存放上传的附件

  1. var storage = multer.diskStorage({  
  2.   destination: function (req, file, cb) {  
  3.     cb(null'/tmp/my-uploads')  
  4.   },  
  5.   filename: function (req, file, cb) {  
  6.     cb(null, file.fieldname + '-' + Date.now())  
  7.   }  
  8. })  
  9.    
  10. var upload = multer({ storage: storage })  

fileFilter

Set this to a function to control which files should be uploaded and which should be skipped. The function should look like this:

设置什么种类的文件可以上传,什么种类的文件被跳过,例如

  1. function fileFilter (req, file, cb) {  
  2.    
  3.   // The function should call `cb` with a boolean   
  4.   // to indicate if the file should be accepted   
  5.    
  6.   // To reject this file pass `false`, like so:   
  7.   cb(nullfalse)  
  8.    
  9.   // To accept the file pass `true`, like so:   
  10.   cb(nulltrue)  
  11.    
  12.   // You can always pass an error if something goes wrong:   
  13.   cb(new Error('I don\'t have a clue!'))  
  14.    
  15. }  

Error handling

When encountering an error, multer will delegate the error to express. You can display a nice error page using the standard express way.

If you want to catch errors specifically from multer, you can call the middleware function by yourself.

当上传过程出现错误,multer将把错误信息发送给express,你可以做一个显示错误的界面。如果你希望从multer获取错误,你可以调用你自己写的中间件

  1. var upload = multer().single('avatar')  
  2.    
  3. app.post('/profile'function (req, res) {  
  4.   upload(req, res, function (err) {  
  5.     if (err) {  
  6.       // An error occurred when uploading   
  7.       return  
  8.     }  
  9.    
  10.     // Everything went fine   
  11.   })  
  12. })  

准备工作

安装express 和 multer模块
npm init 
//输入package.json 的相关信息后会自动生成package.json

//加入express 和 multer模块
npm install express --save
npm install multer --save

例子

后台服务index.js
  1. //引入express模块  
  2. var express = require('express');  
  3. //引入multer模块  
  4. var multer = require ('multer');  
  5. //设置上传的目录,  
  6. //这里指定了一个临时目录(上传后的文件均保存到该目录下),  
  7. //真正开发是一般加入path模块后使用path.join(__dirname,'temp');  
  8. var upload = multer({ dest:  "/home/nodejs/multertest/temp" });  
  9. var app = express();  
  10.   
  11. //处理http://127.0.0.1:3000请求,这个例子没有用到  
  12. app.get('/'function(req, res){  
  13.   res.send('please upload ... ');  
  14. });  
  15.   
  16.   
  17. //单位件上传   
  18. //注意上传界面中的 <input type="file" name="avatar"/>中的name必须是下面代码中指定的名称  
  19. app.post('/singleUpload', upload.single('avatar'), function (req, res, next) {  
  20.   // req.file is the `avatar` file   
  21.   // req.body will hold the text fields, if there were any   
  22.   console.log(req.file);  
  23.   console.log(req.body);  
  24.     
  25.   res.end("上传成功");  
  26. });  
  27.   
  28. //多附件上传  
  29. //注意上传界面中的 <input type="file" name="photos"/>中的name必须是下面代码中指定的名  
  30. app.post('/mulUpload', upload.array('photos', 12), function (req, res, next) {  
  31.   // req.files is array of `photos` files   
  32.   // req.body will contain the text fields, if there were any   
  33.   
  34.   console.log(req.files);  
  35.   console.log(req.body);  
  36.   //res.end(req.file + "<br/><br/>" + req.body);  
  37.   res.end("aaaaa");  
  38.   
  39. })  
  40.   
  41. app.listen(3000);  
前台上传页面代码:
  1. <!DOCTYPE html>  
  2. <html>    
  3. <head>          
  4. <title>NodeJs文件上传</title>  
  5. <meta charset="utf-8"/>  
  6.   
  7. </head>    
  8. <body>    
  9. <h2>单个文件上传</h2>  
  10. <form action="http://127.0.0.1:3000/singleUpload" method="post"  enctype="multipart/form-data">  
  11.     <input type="file" name="avatar" /><br/>  
  12.     <input type="text" name="aaaa" /><br/>  
  13.     <input type="text" name="bbb" /><br/>  
  14.     <input type="submit" value="submit"/><br/>  
  15. </form>  
  16.   
  17. <hr/>  
  18. <h2>多文件上传</h2>  
  19. <form action="http://127.0.0.1:3000/mulUpload" method="post"  enctype="multipart/form-data">  
  20.     <input type="file" name="photos" /><br/>  
  21.     <input type="file" name="photos" /><br/>  
  22.     <input type="file" name="photos" /><br/>  
  23.     <input type="text" name="aaaa" /><br/>  
  24.     <input type="text" name="bbb" /><br/>  
  25.     <input type="submit" value="submit"/><br/>  
  26. </form>  
  27. </body>  
  28. </html>    
单文件上传时后台界面显示内容如下:
{ fieldname: 'avatar',
originalname: '2222222.png',
encoding: '7bit',
mimetype: 'image/png',
destination: '/home/nodejs/multertest/temp',
filename: '9e40b3515891112ebf69b6a1547a83ba',
path: '/home/nodejs/multertest/temp/9e40b3515891112ebf69b6a1547a83ba',
size: 7864 }
{ aaaa: 'aaaa', bbb: 'bbbb' }

多文件上传时后台显示内容如下:
[ { fieldname: 'photos',
originalname: '2222222.png',
encoding: '7bit',
mimetype: 'image/png',
destination: '/home/nodejs/multertest/temp',
filename: 'e21933dc78324e78274d9f69dece94ba',
path: '/home/nodejs/multertest/temp/e21933dc78324e78274d9f69dece94ba',
size: 7864 },
{ fieldname: 'photos',
originalname: 'QQ妾?0151209185325.png',
encoding: '7bit',
mimetype: 'image/png',
destination: '/home/nodejs/multertest/temp',
filename: '4109fccc094d0f1429d80f16dc53dfa3',
path: '/home/nodejs/multertest/temp/4109fccc094d0f1429d80f16dc53dfa3',
size: 2192 },
{ fieldname: 'photos',
originalname: 'signupSubmit.js',
encoding: '7bit',
mimetype: 'application/x-js',
destination: '/home/nodejs/multertest/temp',
filename: 'bcc2e2bf9e9a7cc12eab997c99fec044',
path: '/home/nodejs/multertest/temp/bcc2e2bf9e9a7cc12eab997c99fec044',
size: 1868 } ]
{ aaaa: 'ssssss', bbb: 'ddddd' }
文件属性说明:
属性名 描述 备注
fieldname Field name specified in the form  
originalname Name of the file on the user's computer  
encoding Encoding type of the file  
mimetype Mime type of the file  
size Size of the file in bytes  
destination The folder to which the file has been saved DiskStorage
filename The name of the file within the destination DiskStorage
path The full path to the uploaded file DiskStorage
buffer A Buffer of the entire file MemoryStorage
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值