【问题标题】:Using multer when I upload an image it shows me a message that image has been successfully added but does not added to upload folder当我上传图像时使用 multer 它会显示一条消息,图像已成功添加但未添加到上传文件夹
【发布时间】:2021-12-14 17:49:38
【问题描述】:

这是我在数据库中上传和保存图像的代码,当我这样做时 在邮递员上,它给出了“未定义”的错误,但“文件已上传” 成功',我的图像/文件也没有存储在上传文件夹中

//多文件

const multer = require('multer');

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'originalname');
    },
    filename: (req, file, cb) => {
        cb(null, new Date().toISOString().replace(/:/g, '-') + '-' + file.originalname);
    }
});
const filefilter = (req, file, cb) => {
    if (file.mimetype === 'image/png' || file.mimetype === 'image/jpg' 
        || file.mimetype === 'image/jpeg'){
            cb(null, true);
        }else {
            cb(null, false);
        }
}

const upload = multer({storage: storage, fileFilter: filefilter});

module.exports = {upload}

//图像数据模型

const mongoose=require('mongoose');


const imageSchema=new  mongoose.Schema({

    fileName: {
        type: String,
        required: true
    },
    filePath: {
        type: String,
        required: true
    },
    fileType: {
        type: String,
        required: true
    },
    fileSize: {
        type: String,
        required: true
    }

}, {timestamps: true});

module.exports=mongoose.model('imagedata', imageSchema);

//后控制器

exports.uploadimage = async (req, res, next) => {
    try{

        const file= req.file;
        console.log(file);
        res.status(201).json({messsage:"file uploaded successfully"})

    }catch(error){

        res.status(400).send(error.message)
    }
    

【问题讨论】:

  • 你没有指定你想保存文件的目的地:function(req, file, cb) { cb(null, 'uploads/') },

标签: node.js mongodb multer


【解决方案1】:

你没有指定你想保存文件的目的地 在您的项目中创建一个名为 uploads 的文件夹并按照我在下面提到的进行更改:

destination: (req, file, cb) => {
        cb(null, 'uploads/originalname');
   },

【讨论】:

  • 你用什么来上传文件是邮递员还是一些前端框架,如果你使用前端框架你可以检查文件头是否正在发送,简而言之调试代码无论您是否正确发送文件。
猜你喜欢
  • 1970-01-01
  • 2015-08-15
  • 2017-12-22
  • 1970-01-01
  • 2020-12-02
  • 2013-11-25
  • 2016-07-04
  • 1970-01-01
  • 2015-08-18
相关资源
最近更新 更多