Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 'README-zh-cn.md' up to now #1264

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 38 additions & 2 deletions doc/README-zh-cn.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
**此文档于2016年10月3日翻译时multer的版本是1.2.0,它可能不是最新的!**
**此文档于2024年7月27日更新翻译时multer的版本是1.4.5-lts.1,它可能不是最新的!**
**甚至可能存在翻译错误!你可能需要阅读原版英语[README](../README.md)**
**此文档仅供参考!**

Expand Down Expand Up @@ -30,6 +30,14 @@ Multer 会添加一个 `body` 对象 以及 `file` 或 `files` 对象 到 expres

基本使用方法:

别忘了在你的表单中添加 enctype="multipart/form-data"。

```html
<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" />
</form>
```

```javascript
const express = require('express')
const multer = require('multer')
Expand Down Expand Up @@ -72,6 +80,29 @@ app.post('/profile', upload.none(), function (req, res, next) {
})
```

以下是一个使用multer和HTML表单的示例。特别注意`enctype="multipart/form-data"`和`name="uploaded_file"`字段:

```html
<form action="/stats" enctype="multipart/form-data" method="post">
<div class="form-group">
<input type="file" class="form-control-file" name="uploaded_file">
<input type="text" class="form-control" placeholder="Number of speakers" name="nspeakers">
<input type="submit" value="Get me the stats!" class="btn btn-default">
</div>
</form>
```

然后在你的JavaScript文件中,添加这些行来访问文件和正文。重要的是,你需要在上传函数中使用表单中的`name`字段值。这告诉multer应该在请求中查找文件的哪个字段。如果这些字段在HTML表单和服务器上不相同,你的上传将会失败:

```javascript
const multer = require('multer')
const upload = multer({ dest: './public/data/uploads/' })
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
// req.file 是你在上面的表单中的文件名,这里为 'uploaded_file'
// req.body 将包含文本字段,如果有的话
console.log(req.file, req.body)
});
```
## API

### 文件信息
Expand Down Expand Up @@ -159,7 +190,8 @@ const storage = multer.diskStorage({
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix)
}
})

Expand All @@ -180,6 +212,10 @@ const upload = multer({ storage: storage })

注意 `req.body` 可能还没有完全填充,这取决于向客户端发送字段和文件到服务器的顺序。

要理解回调中使用的调用约定(需要传递null作为第一个参数),请参考
[Node.js 错误处理](https://web.archive.org/web/20220417042018/https://www.joyent.com/node-js/production/design/errors)


#### 内存存储引擎 (`MemoryStorage`)

内存存储引擎将文件存储在内存中的 `Buffer` 对象,它没有任何选项。
Expand Down