multer file.filename和file.path未定义 [英] Multer file.filename and file.path undefined

查看:227
本文介绍了multer file.filename和file.path未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用express和multer将图像上传/存储到磁盘内存中.我的代码简述如下:

I'm trying to upload/store images on disk memory using express and multer. My code in a nutshell below:

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请求时(图像的正确字段名是"photo"),filename函数似乎不会影响该名称.该文件最终以/uploads结尾,但是使用multer的默认命名方案(不是我在文件名函数中定义的自定义名称).

Unfortunately, when I use Postman to send a POST request (the image has the correct fieldname of "photo"), the filename function does not seem to affect the name. The file ends up in /uploads, but with the default naming scheme from multer (not my custom name defined in the filename function).

此外,我的console.log(req.file)行输出如下:

Also, my console.log(req.file) line outputs this:

{ 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.filename,req.file.destinationreq.file.path定义没有值. rel ="nofollow noreferrer"> multer API文档.

Note that there is no value defined for req.file.filename, req.file.destination or req.file.path as specified in the multer API documentation.

知道我在做什么错吗?

Any idea what I'm doing wrong here?

推荐答案

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

Ok, answered my own question. In case it's useful for someone else, my problem was:

我没有使用multer.diskStorage()定义目标和文件名.要提供这些值时,需要使用.diskStorage()方法.正确的用法是:

I did not use multer.diskStorage() to define the destination and filename. You need to use the .diskStorage() method when you want to supply these values. The correct usage would have been:

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作为中间件,例如:

Then you can use multer normally as middleware, e.g.:

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

这篇关于multer file.filename和file.path未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆