【问题标题】:How to handle image upload on node and express?如何处理节点和快递上的图片上传?
【发布时间】:2022-12-17 17:54:48
【问题描述】:

好的,听起来确实如此,但让我解释一下。我使用 mern stack 创建一个 CRUD 应用程序,我首先从后端开始。这是我自己创建的第一个应用程序,所以它非常基础。它只有两个模型,用户模型和产品模型。当我创建 Product 模型时,我添加了一个图像属性并给它一种对象。甚至不确定这是否正确。我完成了身份验证部分,所以我从“创建产品”路线开始。我知道处理图片上传与处理其他属性不同。那么在创建产品时我将如何处理图片上传?我会在下面发布一些代码作为上下文。

我的产品型号:

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: Object,
        default: {}
    },
    createdBy: {
        type: mongoose.Types.ObjectId,
        ref: 'User',
        required: [true, 'Please provide the user'],
      },
}, 
    { timestamps: true }
)

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

我的产品控制器:

const Product = require('../models/Product')

const getAllProducts = async (req, res) => {

    res.send('get All products')
}

const createProduct = async (req, res) => {
    
    res.send('create Product')   
}

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
}

【问题讨论】:

    标签: node.js image express model mern


    【解决方案1】:

    MongoDB/Mongoose 不直接存储图像。如果您想将图像存储到 mongo 数据库,我可以为您提供 2 个选项:

    选项A:将您的图像架构类型更改为“字符串”,然后将您的图像转换为“Base64 字符串”可以用作图像的 src:

    <img src="INSERT_BASE64_STRING_HERE">
    

    有关如何将图像转换为 base64 字符串的更多信息,请参见here

    选项B:拥有一个存储提供商(存储桶,例如 Google 云存储/AWS S3 存储/Azure 存储),然后将图像的 URL 存储在您的 mongo 数据库中。这将比选项 A 复杂得多。如果你想更深入地了解它,这里有一个useful guide,你可以查看

    【讨论】:

      猜你喜欢
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多