Joe*_*M-H 2 javascript node.js express multer
我正在尝试使用 express 和 multer 在磁盘内存上上传/存储图像。我的代码简而言之如下:
const express = require('express')
Run Code Online (Sandbox Code Playgroud)
const multer = require('multer');
const upload = multer({
destination: function(req, file, cb) {
cb(null, 'uploads/')
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
Run Code Online (Sandbox Code Playgroud)
app.post('/', upload.single('photo'), function(req, res) {
console.log(req.file);
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,当我使用 Postman 发送 POST 请求时(图像具有正确的字段名称“照片”),该filename功能似乎不会影响名称。该文件最终在 /uploads 中,但使用来自 multer 的默认命名方案(不是我在文件名函数中定义的自定义名称)。
此外,我的console.log(req.file)线路输出这个:
{ fieldname: 'photo',
originalname: 'test.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 02 00 00 01 00 01 00 00 ff db 00 43 00 08 06 06 07 06 05 08 07 07 07 09 09 08 0a 0c 14 0d 0c 0b 0b 0c 19 12 13 0f ... >,
size: 85404 }
Run Code Online (Sandbox Code Playgroud)
请注意,有没有对定义的值req.file.filename,req.file.destination或者req.file.path作为在指定multer API文档。
知道我在这里做错了什么吗?
好的,回答了我自己的问题。如果它对其他人有用,我的问题是:
我没有使用 multer.diskStorage() 来定义目标和文件名。.diskStorage()当您想要提供这些值时,您需要使用该方法。正确的用法是:
const multer = require('multer');
const storage = multer.diskStorage({ // notice you are calling the multer.diskStorage() method here, not multer()
destination: function(req, file, cb) {
cb(null, 'uploads/')
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
const upload = multer({storage}); //provide the return value from
Run Code Online (Sandbox Code Playgroud)
然后你可以正常使用multer作为中间件,例如:
app.post('/', upload.single('photo'), function(req, res) {
// do what you want with req.file
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6724 次 |
| 最近记录: |