node+multer实现图片上传的示例代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

node+multer实现图片上传的示例代码

Dlingling   2020-05-17 我要评论

最近在学习node实现一个后台管理系统,用到了图片上传,有一些小问题记录一下~

直接上代码,问题都记录在注释里~

const express = require('express');
const path = require('path');
const multer = require('multer');
const app = new express();

// 设置静态目录 第一个参数为虚拟的文件前缀,实际上文件系统中不存在
// 可以用public做为前缀来加载static文件夹下的文件了
app.use('/public', express.static(path.join(__dirname, './static')));

// 根据当前文件目录指定文件夹
const dir = path.resolve(__dirname, '../static/img');
// 图片大小限制KB
const SIZELIMIT = 500000;

const storage = multer.diskStorage({
  // 指定文件路径
  destination: function(req, file, cb) {
    // !!!相对路径时以node执行目录为基准,避免权限问题,该目录最好已存在*
    // cb(null, './uploads');
    cb(null, dir);
  },
  // 指定文件名
  filename: function(req, file, cb) {
    // filedname指向参数key值
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({
  storage: storage
});

app.post('/upload', upload.single('file'), (req, res) => {
  // 即将上传图片的key值 form-data对象{key: value}
  // 检查是否有文件待上传
  if (req.file === undefined) {
    return res.send({
      errno: -1,
      msg: 'no file'
    });
  }
  const {size, mimetype, filename} = req.file;
  const types = ['jpg', 'jpeg', 'png', 'gif'];
  const tmpTypes = mimetype.split('/')[1];
  // 检查文件大小
  if (size >= SIZELIMIT) {
    return res.send({
      errno: -1,
      msg: 'file is too large'
    });
  }
  // 检查文件类型
  else if (types.indexOf(tmpTypes) < 0) {
    return res.send({
      errno: -1,
      msg: 'not accepted filetype'
    });
  }
  // 路径可根据设置的静态目录指定
  const url = '/public/img/' + filename;
  res.json({
    errno: 0,
    msg: 'upload success',
    url
  });
});

app.listen(3000, () => {
  console.log('service start');
});

附上文档参考链接:
express框架
path模块
multer
最后再附赠一个node自动重启工具nodemon

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们