node multer上传图片(三)

830 阅读1分钟

文章主要记录如何实现使用express连接数据库,做增删改查,关联数据库,封装路由,jsonwebtoken鉴权,bcrypt登录密码加密,multer文件上传和一些请求数据的处理,开发日志记录。

multer上传图片

multer注意事项
multer上传格式是form-data

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
// 引入multer
const multer = require('multer');

const storage = multer.diskStorage({
// 上传图片的存放位置在uploads
  destination: function(req, file, cb) {
    cb(null, './uploads/');
  },
  // windows下使用-代替:
  filename: function(req, file, cb) {
    cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname)
  }
}) 

const fileFilter = (req, file, cb) => {
  //判断上传图片类型
  if (file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(null, false);
  }
}
// limit上传图片尺寸限制
const uploads = multer({
  storage: storage, 
  limit: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter
});

// 接受一个文件。这个文件的信息保存在 req.file。最终存放在uploads
router.post('/', uploads.single('productImage'), (req, res, next) => {

  console.log(req.file)
  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 => {
      res.status(201).json({
        message: "created product successfully",
        createdProduct: {
          name: result.name,
          price: result.price,
          _id: result._id,
          productImage: result.productImage,
          request: {
            type: 'GET',
            url: 'http://localhost:3000/products/' + result._id
          }
        }
      })
  })
  .catch(err => {
    res.status(500).json({
      error: err
    })
  })

})

当前项目目录