multer 基础教程(英文版)
Multer is a node.js middleware for handling multipart/form-data
, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
NOTE: Multer will not process any form which is not multipart (multipart/form-data
).
Translations
This README is also available in other languages:
- 简体中文 (Chinese)
- 한국어 (Korean)
- Русский язык (Russian)
Installation
$ npm install --save multer
Usage
Multer adds a body
object and a file
or files
object to the request
object. The body
object contains the values of the text fields of the form, the file
or files
object contains the files uploaded via the form.
Basic usage example:
Don't forget the enctype="multipart/form-data"
in your form.
<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" />
</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
})
In case you need to handle a text-only multipart form, you should use the .none()
method:
var express = require('express')
var app = express()
var multer = require('multer')
var upload = multer() app.post('/profile', upload.none(), function (req, res, next) {
// req.body contains the text fields
})
API
File information
Each file contains the following information:
Key | Description | Note |
---|---|---|
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 |
multer(opts)
Multer accepts an options object, the most basic of which is the dest
property, which tells Multer where to upload the files. In case you omit the options object, the files will be kept in memory and never written to disk.
By default, Multer will rename the files so as to avoid naming conflicts. The renaming function can be customized according to your needs.
The following are the options that can be passed to Multer.
Key | Description |
---|---|
dest or storage |
Where to store the files |
fileFilter |
Function to control which files are accepted |
limits |
Limits of the uploaded data |
preservePath |
Keep the full path of files instead of just the base name |
In an average web app, only dest
might be required, and configured as shown in the following example.
var upload = multer({ dest: 'uploads/' })
If you want more control over your uploads, you'll want to use the storage
option instead of dest
. Multer ships with storage engines DiskStorage
and MemoryStorage
; More engines are available from third parties.
.single(fieldname)
Accept a single file with the name fieldname
. The single file will be stored in req.file
.
.array(fieldname[, maxCount])
Accept an array of files, all with the name fieldname
. Optionally error out if more than maxCount
files are uploaded. The array of files will be stored in req.files
.
.fields(fields)
Accept a mix of files, specified by fields
. An object with arrays of files will be stored in req.files
.
fields
should be an array of objects with name
and optionally a maxCount
. Example:
[
{ name: 'avatar', maxCount: 1 },
{ name: 'gallery', maxCount: 8 }
]
.none()
Accept only text fields. If any file upload is made, error with code "LIMIT_UNEXPECTED_FILE" will be issued.
.any()
Accepts all files that comes over the wire. An array of files will be stored in req.files
.
WARNING: Make sure that you always handle the files that a user uploads. Never add multer as a global middleware since a malicious user could upload files to a route that you didn't anticipate. Only use this function on routes where you are handling the uploaded 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 })
There are two options available, destination
and filename
. They are both functions that determine where the file should be stored.
destination
is used to determine within which folder the uploaded files should be stored. This can also be given as a string
(e.g. '/tmp/uploads'
). If no destination
is given, the operating system's default directory for temporary files is used.
Note: You are responsible for creating the directory when providing destination
as a function. When passing a string, multer will make sure that the directory is created for you.
filename
is used to determine what the file should be named inside the folder. If no filename
is given, each file will be given a random name that doesn't include any file extension.
Note: Multer will not append any file extension for you, your function should return a filename complete with an file extension.
Each function gets passed both the request (req
) and some information about the file (file
) to aid with the decision.
Note that req.body
might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.
MemoryStorage
The memory storage engine stores the files in memory as Buffer
objects. It doesn't have any options.
var storage = multer.memoryStorage()
var upload = multer({ storage: storage })
When using memory storage, the file info will contain a field called buffer
that contains the entire file.
WARNING: Uploading very large files, or relatively small files in large numbers very quickly, can cause your application to run out of memory when memory storage is used.
limits
An object specifying the size limits of the following optional properties. Multer passes this object into busboy directly, and the details of the properties can be found on busboy's page.
The following integer values are available:
Key | Description | Default |
---|---|---|
fieldNameSize |
Max field name size | 100 bytes |
fieldSize |
Max field value size (in bytes) | 1MB |
fields |
Max number of non-file fields | Infinity |
fileSize |
For multipart forms, the max file size (in bytes) | Infinity |
files |
For multipart forms, the max number of file fields | Infinity |
parts |
For multipart forms, the max number of parts (fields + files) | Infinity |
headerPairs |
For multipart forms, the max number of header key=>value pairs to parse | 2000 |
Specifying the limits can help protect your site against denial of service (DoS) attacks.
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. Also, if you want to catch only the Multer errors, you can use the MulterError
class that is attached to the multer
object itself (e.g. err instanceof multer.MulterError
).
var multer = require('multer')
var upload = multer().single('avatar') app.post('/profile', function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
} else if (err) {
// An unknown error occurred when uploading.
} // Everything went fine.
})
})
Custom storage engine
For information on how to build your own storage engine, see Multer Storage Engine.
License
multer 基础教程(英文版)的更多相关文章
- multer 基础教程(中文版)
此文档于2016年10月3日翻译时multer的版本是1.2.0,它可能不是最新的! 甚至可能存在翻译错误!你可能需要阅读原版英语README 此文档仅供参考! Multer Multer 是一个 n ...
- Android UI基础教程 目录
从csdn下载了这本英文版的书之后,又去京东搞了一个中文目录下来.对照着看. 话说,这本书绝对超值.有money的童鞋看完英文版记得去买中文版的~~ Android UI基础教程完整英文版 pdf+源 ...
- Java 初学者帮助文档以及基础教程
一下午的时间,大致看了一下Java的文档,进一步熟悉了Java的大体框架和结构,整理了一下有用的资源. 帮助文档: JSE 8 API 英文版 在线HTML格式:http://docs.oracle. ...
- OpenVAS漏洞扫描基础教程之连接OpenVAS服务
OpenVAS漏洞扫描基础教程之连接OpenVAS服务 连接OpenVAS服务 当用户将OpenVAS工具安装并配置完后,用户即可使用不同的客户端连接该服务器.然后,对目标主机实施漏洞扫描.在本教程中 ...
- matlab基础教程——根据Andrew Ng的machine learning整理
matlab基础教程--根据Andrew Ng的machine learning整理 基本运算 算数运算 逻辑运算 格式化输出 小数位全局修改 向量和矩阵运算 矩阵操作 申明一个矩阵或向量 快速建立一 ...
- <<Bootstrap基础教程>> 新书出手,有心栽花花不开,无心插柳柳成荫
并非闲的蛋疼,做技术也经常喜欢蛋疼,纠结于各种技术,各种需求变更,还有一个很苦恼的就是UI总是那么不尽人意.前不久自己开源了自己做了多年的仓储项目(开源地址:https://github.com/he ...
- Memcache教程 Memcache零基础教程
Memcache是什么 Memcache是danga.com的一个项目,来分担数据库的压力. 它可以应对任意多个连接,使用非阻塞的网络IO.由于它的工作机制是在内存中开辟一块空间,然后建立一个Hash ...
- Selenium IDE 基础教程
Selenium IDE 基础教程 1.下载安装 a 在火狐浏览其中搜索附件组件,查找 Selenium IDE b 下载安装,然后重启firefox 2.界面讲解 在菜单- ...
- html快速入门(基础教程+资源推荐)
1.html究竟是什么? 从字面上理解,html是超文本标记语言hyper text mark-up language的首字母缩写,指的是一种通用web页面描述语言,是用来描述我们打开浏览器就能看到的 ...
随机推荐
- Python骚操作:Python控制Excel实现自动化办公!
1.安装 2.操作一个简单的Excel文档 操作注释及代码: 操作完成后,数据存储结果如下: 3. 操作简单Excel文档并添加数据格式 操作代码如下:附带数据格式的定义 操作效果 ...
- C语言程序设计100例之(2):一元二次方程
例2 一元二次方程 [题目描述] 输入系数a.b和c,求方程ax2+bx+c=0的根. [输入格式] 输入数据有多组.每组数据包括三个系数a,b,c.当a=0时,输入数据结束. [输出格式] 输出 ...
- 数据防泄漏 | 禁止PrintScreen键
在数据防泄漏软件,通常会禁止 PrintScreen 键,防止通过截屏来将数据保存为图片而导致泄密. 这类软件如果想要实现是比较简单的,但是想要将功能做的强大些,还是需要下功夫的.以前使用过一款数据防 ...
- nodejs环境下的socket通信
结构: socket是应用层和传输层的桥梁.(传输层之上的协议所涉及的数据都是在本机处理的,并没进入网络中) 涉及数据: socket所涉及的数据是报文,是明文. 作用: 建立长久链接,供网络上的两个 ...
- Netty — 心跳检测和断线重连
一.前言 由于在通信层的网络连接的不可靠性,比如:网络闪断,网络抖动等,经常会出现连接断开.这样对于使用长连接的应用而言,当突然高流量冲击势必会造成进行网络连接,从而产生网络堵塞,应用响应速度下降,延 ...
- java基础(25):Properties、序列化流、打印流、commons-IO
1. Properties类 1.1 Properties类介绍 Properties 类表示了一个持久的属性集.Properties 可保存在流中或从流中加载.属性列表中每个键及其对应值都是一个字符 ...
- PHP中设计模式以及魔术方法
1.设计模式 1.1单例模式 口诀:三私一公 1.私有的静态属性用来保存对象的单例 2.私有的构造方法用来阻止在类的外部实例化 3.私有的__clone阻止在类的外部clo ...
- 机器学习实战:基于Scikit-Learn和TensorFlow 读书笔记 第6章 决策树
数据挖掘作业,要实现决策树,现记录学习过程 win10系统,Python 3.7.0 构建一个决策树,在鸢尾花数据集上训练一个DecisionTreeClassifier: from sklearn. ...
- ElasticSearch安装及运行的坑
一.确认centos系统是为64位的,x86的不可以安装 1. 下载elasticsearch包 2. 用 tar -zxvf 解压包 3. 增加一个elk用户,elasticsearch7不可用ro ...
- BayaiM__MySQL错误对照表
BayaiM__MySQL错误对照表 原创 作者:bayaim 时间:2016-06-16 09:16:29 33 0删除编辑 ------------------------------------ ...