最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

Multer req.file.path是未定义

IT培训 admin 3浏览 0评论

Multer req.file.path是未定义

对不起,这个简单的问题。我只是新的Node.js,并设法使与快递一个RESTAPI。对于文件上传我用从NPM multer。一切都做工精细。但是,当我尝试使用req.file.path访问POST方法multer财产是抛出这条消息:

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

我也试图让像“MIME类型”,但同样的错误只是属性名称更改multer提供的其他财产。我使用的邮递员发送数据。这里是我的代码片段。

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);

我无法找到解决方案。我已经查了几个从计算器解决方案,但没有找到任何解决办法。

回答如下:

如果你使用邮递员请确保您选择“页眉和体内请确保您选择表单数据和关键是“productImage”的类型是“内容类型”,”多/ form-data的文件,然后值是文件你想上传

Multer req.file.path是未定义

对不起,这个简单的问题。我只是新的Node.js,并设法使与快递一个RESTAPI。对于文件上传我用从NPM multer。一切都做工精细。但是,当我尝试使用req.file.path访问POST方法multer财产是抛出这条消息:

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

我也试图让像“MIME类型”,但同样的错误只是属性名称更改multer提供的其他财产。我使用的邮递员发送数据。这里是我的代码片段。

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);

我无法找到解决方案。我已经查了几个从计算器解决方案,但没有找到任何解决办法。

回答如下:

如果你使用邮递员请确保您选择“页眉和体内请确保您选择表单数据和关键是“productImage”的类型是“内容类型”,”多/ form-data的文件,然后值是文件你想上传

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论