Multer不上传,但它不会给我任何错误。

问题描述 投票:0回答:1

我在我的应用程序中使用multer上传图片来创建课程,我的课程有图片,我有一个表单从用户那里获取数据。upload.single('images') 当我点击保存按钮时,我不会得到任何错误,我的服务器会像卡在一个中间件中一样工作,当我去我的上传文件夹时,我没有看到任何图像加载!如果我加载图像,我会将课程保存在我的数据库中,这是Mongo。但我没有发现课程也保存了。我已经检查了 enctype="multipart/form-data" 这是我的表格,这是我的中间件代码。

const multer = require("multer");
const mkdirp = require("mkdirp");
const fs = require("fs");

const getDirImage = () => {
  let year = new Date().getFullYear();
  let month = new Date().getMonth() + 1;
  let day = new Date().getDay();

  return `./public/uploads/images/${year}/${month}/${day}`;
};

const ImageStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    let dir = getDirImage();
    mkdirp(dir).then(made => {
        console.log(`File made on ${made}`);   
    });
  },
  filename: (req, file, cb) => {
    let filePath = getDirImage() + "/" + file.originalname;
    if (!fs.existsSync(filePath)) cb(null, file.originalname);
    else cb(null, Date.now() + "-" + file.originalname);
  },
});

const uploadImage = multer({
  storage: ImageStorage,
  limits: {
    fileSize: 1024 * 1024 * 10,
  },
});

module.exports = uploadImage;

这是中间件,我把它引用到我的路由控制器处理程序上

router.post("/courses/create", upload.single("images"), convertFileToField.handle, courseValidator.handle(), courseController.storeCourse);

这就是 convertFileToField 编码

const middleware = require('./middleware');

class ConvertFiletoField extends middleware {
  handle(req, res, next) {
    if (!req.file)
        req.body.images = undefined;
    else 
        req.body.images = req.file.filename;

    next();
  }
}

module.exports = new ConvertFiletoField();

这就是 courseValidator 中间件代码

const validator = require('./validator');
const Course = require("app/models/Course");
const path = require("path");
const { check } = require("express-validator/check");

class courseValidator extends validator {
  handle() {
    return [
      check("title")
        .not()
        .isEmpty()
        .withMessage("فیلد عنوان نمیتواند خالی بماند")
        .custom(async (value) => {
          const course = await Course.findOne({ slug: this.slug(value)});
          if (course) {
            throw new Error('we have this course on our site !!!!')
          }
        }),

      check('images')
        .custom(async value => {
          if (! value) {
            throw new Error('You need to enter a course !');
          }
          let fileExt = ['.png', '.jpg', 'jpeg', '.svg'];

          if (! fileExt.includes(path.extname(value)))
            throw new Error('the course extention is not valid !'); 
        }),

    ];
  }

  slug(title) {
    return title.replace(/([^۰-۹آ-یa-z0-9]|-)+/g, "-");
  }
}

module.exports = new courseValidator();

最后,这是后路由处理程序

const controller = require("app/http/controllers/controller");
const Course = require("app/models/Course");
const fs = require('fs');
const path = require("path");
const sharp = require("sharp");

class courseController extends controller {
  showCourses(req, res) {
    const courses = Course.find({}).sort({ createdAt: -1 });
    res.render("admin/courses/index", { courses: courses });
  }

  createCourse(req, res) {
    res.render("admin/courses/create");
  }

  async storeCourse(req, res) {
    let status = await this.validationData(req);
    if (!status) {
      // For Deleting the saved image because of having validation error
      if (req.file)
        fs.unlink(req.file.path, (err) => {
          console.log(err);
        });
      return this.back(req, res);
    }

    // Create the Course
    let images = this.imageResize(req.file);
    const { title, type, body, price, tags } = req.body;

    const newCourse = new Course({
      user: req.user._id,
      title,
      type,
      slug: this.slug(),
      body,
      images: JSON.stringify(images),
      price,
      tags,
    });
    await newCourse.save();
    return res.redirect("/admin/courses");
  }

  imageResize(image) {
    let imageInfo = path.parse(image.path);

    let addressImage = {};
    addressImage["original"] = `${imageInfo}/${image.filename}`;

    const resize = (size) => {
      let imageName = `${imageInfo.name}-${size}${imageInfo.ext}`;

      addressImage[size] = this.getUrlImage(`${image.destination}/${imageName}`);

      sharp(image.path)
        .resize(size, null)
        .toFile(`${image.destination}/${imageName}`)
    };

    [1080, 720, 480].map(resize);
  }

  getUrlImage(dir) {
    return dir.substr(8);
  }

  slug(title) {
    return title.replace(/([^۰-۹آ-یa-z0-9]|-)+/g, "-");
  }
}

module.exports = new courseController();

我已经做了一切,我可以和我已经尝试了所有的解决方案加载图像,但我得到错误在我的。courseValidation 中间件。

请说说与multer相关的解决方案。我将尝试一下。

javascript node.js express multer
1个回答
0
投票

中的 destination 科室 diskStorage 你必须在回调函数中返回目录的名称。你的中间件在这部分停止了,因为你没有调用 cb 的功能。

 destination: (req, file, cb) => {
    let dir = getDirImage();
    mkdirp(dir).then(made => {
        console.log(`File made on ${made}`);
        cb(made)
    });
  }

0
投票

这里需要定义中间件函数

router.post("/courses/create", multerMiddleWare,..{...});

    const multerMiddleWare = (req, res, next) => {
      uploadImage(req, res,
          (error) => {
            if (!error) return next();
            return next('error');
          });
    };

const uploadImage = multer({
  storage: ImageStorage,
  limits: {
    fileSize: 1024 * 1024 * 10,
  },
}).single("images");
© www.soinside.com 2019 - 2024. All rights reserved.