node之上传图片

旧巷老猫 提交于 2020-02-05 23:58:39
const express = require('express')
const router = express.Router()
const multer = require('multer')

// var upload = multer({ dest: 'uploads/' })
var storage = multer.diskStorage({
  // 设置上传文件路径
  destination: function(req, file, cb) {
    cb(null, './uploads')
  },
  // 给上传文件重命名,获取添加后缀名
  filename: function(req, file, cb) {
    var fileFormat = (file.originalname).split('.')
    // 给图片加上时间戳格式防止重命名
    cb(null, file.fieldname + '-' + Date.now() + '.' + fileFormat[fileFormat.length - 1])
  }
})

var upload = multer({
  storage: storage
})

/**
 * @api {post} /file/upload 图片上传
 * @apiName uploadImage
 * @apiGroup File
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
*/

router.post('/upload', upload.single('image'), function (req, res, next) {
  // image 为key,需要和前端保持一致 {image: formData}
  if (!req.file) return res.send('上传失败')
  let {mimetype, size, filename} = req.file
  // 白名单
  const whiteList = ['image/jpg', 'image/jpeg', 'image/JPG', 'image/JPEG', 'image/png', 'image/PNG', 'image/gif', 'image/GIF']
  // 5M 5 * 1024 * 1024
  if (size > 5 * 1024 * 1024) {
    res.send({err: -1, msg: '上传失败,图片尺寸不能超过5M'})
  } else if (whiteList.indexOf(mimetype) == -1) { //  格式不准确
    res.send({err: -1, msg: '上传失败,图片格式不正确'})
  } else {
    // 上传成功返回图片路径
    res.send({err: 0, msg: '上传成功', img: `/image/${filename}`})
  }
})

module.exports = router
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!