nodejs - multer 模块教程,使用 multer 上传附件
multer 在request对象中加入了body和file或files属性,body属性包含了form中的文本内容,file或files包含了form 中的附件数据
- 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
- })
key | description |
---|---|
dest or storage | Where to store the files |
fileFilter | Function to control which files are accepted |
limits | Limits of the uploaded data |
.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.
你可以使用硬盘存储模式设置在哪里存放上传的附件
- var storage = multer.diskStorage({
- destination: function (req, file, cb) {
- cb(null, '/tmp/my-uploads')
- },
- filename: function (req, file, cb) {
- cb(null, file.fieldname + '-' + Date.now())
- }
- })
- 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:
设置什么种类的文件可以上传,什么种类的文件被跳过,例如
- function fileFilter (req, file, cb) {
- // The function should call `cb` with a boolean
- // to indicate if the file should be accepted
- // To reject this file pass `false`, like so:
- cb(null, false)
- // To accept the file pass `true`, like so:
- cb(null, true)
- // You can always pass an error if something goes wrong:
- cb(new Error('I don\'t have a clue!'))
- }
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获取错误,你可以调用你自己写的中间件
- var upload = multer().single('avatar')
- app.post('/profile', function (req, res) {
- upload(req, res, function (err) {
- if (err) {
- // An error occurred when uploading
- return
- }
- // Everything went fine
- })
- })
准备工作
npm init
//输入package.json 的相关信息后会自动生成package.json
//加入express 和 multer模块
npm install express --save
npm install multer --save
例子
- //引入express模块
- var express = require('express');
- //引入multer模块
- var multer = require ('multer');
- //设置上传的目录,
- //这里指定了一个临时目录(上传后的文件均保存到该目录下),
- //真正开发是一般加入path模块后使用path.join(__dirname,'temp');
- var upload = multer({ dest: "/home/nodejs/multertest/temp" });
- var app = express();
- //处理http://127.0.0.1:3000请求,这个例子没有用到
- app.get('/', function(req, res){
- res.send('please upload ... ');
- });
- //单位件上传
- //注意上传界面中的 <input type="file" name="avatar"/>中的name必须是下面代码中指定的名称
- app.post('/singleUpload', upload.single('avatar'), function (req, res, next) {
- // req.file is the `avatar` file
- // req.body will hold the text fields, if there were any
- console.log(req.file);
- console.log(req.body);
- res.end("上传成功");
- });
- //多附件上传
- //注意上传界面中的 <input type="file" name="photos"/>中的name必须是下面代码中指定的名
- app.post('/mulUpload', 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
- console.log(req.files);
- console.log(req.body);
- //res.end(req.file + "<br/><br/>" + req.body);
- res.end("aaaaa");
- })
- app.listen(3000);
- <!DOCTYPE html>
- <html>
- <head>
- <title>NodeJs文件上传</title>
- <meta charset="utf-8"/>
- </head>
- <body>
- <h2>单个文件上传</h2>
- <form action="http://127.0.0.1:3000/singleUpload" method="post" enctype="multipart/form-data">
- <input type="file" name="avatar" /><br/>
- <input type="text" name="aaaa" /><br/>
- <input type="text" name="bbb" /><br/>
- <input type="submit" value="submit"/><br/>
- </form>
- <hr/>
- <h2>多文件上传</h2>
- <form action="http://127.0.0.1:3000/mulUpload" method="post" enctype="multipart/form-data">
- <input type="file" name="photos" /><br/>
- <input type="file" name="photos" /><br/>
- <input type="file" name="photos" /><br/>
- <input type="text" name="aaaa" /><br/>
- <input type="text" name="bbb" /><br/>
- <input type="submit" value="submit"/><br/>
- </form>
- </body>
- </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:
下一篇: nodejs Multer 中间件
推荐阅读
-
使用 multer 上传 NodeJs 文件
-
vue+express 实现文件上传,multer 模块使用教程
-
使用 multer 上传 NodeJs 文件
-
[nodejs] multer(图像、文件上传处理模块)
-
使用 nodejs 文件上传组件 multer
-
nodejs - multer 模块教程,使用 multer 上传附件
-
multer] 文件上传模块使用 [stream] 读取数据。
-
关于使用 multer 实现文件上传和下载的 NodeJs
-
nodeJs 中间件 Multer 解说_使用 express 实现将本地文件/图片上传到服务器指定目录-3。
-
学习 nodejs multer 模块(实现图片上传)