【问题标题】:Multer req.file.path is undefinedMulter req.file.path 未定义
【发布时间】:2018-07-21 16:20:14
【问题描述】:

抱歉这个简单的问题。我只是 node.js 的新手,并尝试用 express 制作一个 RESTapi。对于文件上传,我使用来自 npm 的 multer。一切正常。但是当我尝试使用 req.file.path 在 post 方法中访问 multer 属性时,它会抛出以下消息:

{
    "error": {
        "message": "Cannot read property 'path' of undefined"
    }
}

我还尝试在 multer 中获取其他可用属性,例如“mimetype”,但同样的错误只是属性名称已更改。我正在使用 postman 发送数据。 这是我的代码 sn-ps。

product.js

import express from 'express';
import mongoose from 'mongoose';
import Product from '../models/product.model';
import multer from 'multer';

const router = express.Router();

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './uploads');
    },
    filename: (req, file, cb) => {
        cb(null, `${new Date().toISOString().replace(/:/g, '-')}${file.originalname}`);
    }
});

const fileFilter = (req, file, cb) => {
    // reject a file
    if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        cb(null, false);
    } else {
        cb(new Error('Only .jpeg or .png files are accepted'), true);   
    }
};

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 5
    },
    fileFilter: fileFilter
});

router.post('/', upload.single('productImage'), (req, res, next) => {
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price,
        productImage: req.file.path
    });
    product.save().then(result => {
        console.log(result);
        res.status(201).json({
            message: 'Created product successfully',
            createdProduct: {
                name: result.name,
                price: result.price,
                _id: result._id,
                request: {
                    type: 'GET',
                    url: `http://localhost:3000/products/${result._id}`
                }
            }
        });
    }).catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
});

product.model.ts

import mongoose from 'mongoose';

const productSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {type: String, required: true},
    price: {type: Number, required: true},
    productImage: { type: String, required: true }
});

module.exports = mongoose.model('Product', productSchema);

我找不到解决方案。我从 stackoverflow 检查了几个解决方案,但没有找到任何解决方案。

【问题讨论】:

  • 我没看到你打电话给req.file.path
  • 对不起。它在邮政路线中。我只是试图从 multer 那里获得其他可用的财产。参见 productImage: req.file.path on post 方法
  • 您能在创建新产品之前登录req.file 并向我们展示输出吗?
  • @Striped 会出现未定义

标签: javascript node.js express postman multer


【解决方案1】:

如果您使用邮递员,请确保在标题和正文中选择“Content-Type”“multipart/form-data”,请确保选择 form-data,键是“productImage”,类型是文件,然后是值是你要上传的文件

【讨论】:

  • 嗯,我做到了,但没有运气:(
  • 你能不能尝试 require 模块而不是导入它
【解决方案2】:

使用 cURL 文件名“image”发送文件

curl -X PUT  http://www.example.com  -F "image=@/file-path"

在服务器端获取文件名

upload(req, res, (err)=> {
            if (err) {
              console(err);
            }
            let filePath = req.files.image.file; // image is filename in cURL request
});

【讨论】:

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