postman 如何使用multer处理mern堆栈中的图像上传?

cs7cruho  于 2022-12-18  发布在  Postman
关注(0)|答案(1)|浏览(200)

我正在创建一个MERN堆栈应用程序,并在React前端,我打算有一个表单添加一个产品,该表单将有很多输入,包括一个图像上传选项。我想知道如何处理图像上传从快递方面使用Multer。我已经使用了他们的文档,但我不确定我写的代码是否正确。我还没有创建前端,所以我现在正在使用postman来测试API。我如何测试postman的图片上传功能是否正常工作呢?我会把我目前为止写的代码贴出来。
产品型号:

const mongoose = require('mongoose')

const ProductSchema = new mongoose.Schema({
    name:{
        type: String,
        required: [true, 'please provide a product name'],
        maxlength: 20,
        minlength: 3
    },
    category: {
        type: String,
        required: [true, 'please provide a category'],
        maxlength: 20,
        minlength: 3
    },
    quantity: {
        type: Number,
        required: [true, 'please provide the quantity']
    },
    price: {
        type: Number,
        required: [true, 'please provide the price']
    },
    description: {
        type: String,
        required: [true, 'please provide the description'],
        trim: true
    },
    image: {
        type: String
    },
    createdBy: {
        type: mongoose.Types.ObjectId,
        ref: 'User',
        required: [true, 'Please provide the user'],
    }, }, 
    { timestamps: true } )

module.exports = mongoose.model('Product', ProductSchema)

文件上传.js:

const multer = require('multer')
const { v4: uuidv4 } = require('uuid')

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, '../uploads')
    },
    filename: function(req, file, cb){
        cb(null, uuidv4() + '-' + Date.now() + path.extname(file.originalname) )
    }
})

const fileFilter = (req, file, cb) => {
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png']
    if(allowedTypes.includes(file.mimetype)) {
        cb(null, true)
    }else(
        cb(null, false)
    )
}

const upload = multer({storage, fileFilter})

module.exports = upload

产品工艺路线:

const express = require('express')
const router = express.Router()
const upload = require('../utils/fileUpload')

const {getAllProducts, createProduct, getProduct, updateProduct, deleteProduct} = require('../controllers/products')

router.route('/').post(upload.single('image'), createProduct).get(getAllProducts)
router.route('/:id').get(getProduct).patch(updateProduct).delete(deleteProduct)

module.exports = router


产品控制员:

const Product = require('../models/Product')
const { StatusCodes } = require('http-status-codes')
const { BadRequestError, NotFoundError } = require('../errors') 

const createProduct = async (req, res) => {
    req.body.createdBy = req.user.userId
    const product = await Product.create({...req.body, image: req.file})
    res.send('create Product')   
}

const getAllProducts = async (req, res) => {
    res.send('get All products')
}

const getProduct = async (req, res) => {
    res.send('get product')
}

const updateProduct = async (req, res) => {
    res.send('update product')
}

const deleteProduct = async (req, res) => {
    res.send('delete product')
}

module.exports = {
    getAllProducts, createProduct, getProduct, updateProduct, deleteProduct
}
k3fezbri

k3fezbri1#

您可以将参数类型更改为file from postman,以便在发送请求时尝试上载文件:

相关问题