【问题标题】:Multer file.filename and file.path undefinedMulter file.filename 和 file.path 未定义
【发布时间】:2018-04-17 00:40:53
【问题描述】:

我正在尝试使用 express 和 multer 在磁盘内存中上传/存储图像。简而言之,我的代码如下:

const express = require('express')
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())
    }
});
app.post('/', upload.single('photo'), function(req, res) {
    console.log(req.file);
});

不幸的是,当我使用 Postman 发送 POST 请求时(图像具有正确的“照片”字段名),filename 函数似乎不会影响名称。该文件以 /uploads 结尾,但使用 multer 的默认命名方案(不是我在 filename 函数中定义的自定义名称)。

另外,我的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 }

请注意,req.file.filenamereq.file.destinationreq.file.path 未定义 no 值,如 multer API documentation 中指定的那样。

知道我在这里做错了什么吗?

【问题讨论】:

    标签: javascript node.js express multer


    【解决方案1】:

    好的,回答了我自己的问题。如果它对其他人有用,我的问题是:

    我没有使用 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 
    

    那么就可以正常使用multer作为中间件了,例如:

    app.post('/', upload.single('photo'), function(req, res) {
        // do what you want with req.file
    });
    

    【讨论】:

      【解决方案2】:

      另外请记住,如果您想访问原始名称(通过网络发送的文件的名称),您必须使用 file.originalname 而不是 file.filename

      【讨论】:

        猜你喜欢
        • 2020-12-17
        • 2018-07-21
        • 2018-08-06
        • 1970-01-01
        • 2021-10-02
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        • 2016-06-21
        相关资源
        最近更新 更多