相关链接:multer

安装multer

npm install multer -S

配置文件

//app-config.js
// ES6写法 没有用Babel转的用require: const path = require("path")
// 具体还需要其他配置的可以去上方链接的仓库去看文档
import path from "path";
import fs from "fs";
import multer from "multer";

//用户上传文件配置
export const dist = multer.diskStorage({
    //设置存储路径
    destination: function (req, file, cb) {
        let date = new Date()
        let years = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        //上传文件存储文件夹按年月区分 注意 路径是从项目根目录开始的
        //路径必须存在且正确,否则将不会存储到磁盘中
        let filePath = './src/upload/'+years+'/'+month+'/'+day+'/'
        //判断文件夹是否存在 不存在则创建
        fs.stat(filePath, function (err, stats) {
            if (!stats) {
                fs.mkdir(filePath, {recursive: true}, () => {
                    cb(null, filePath)
                }); //Create dir in case not found
            }else{
                cb(null, filePath)
            }
        });
      },
      //限制配置
      limits: {
        fileSize: 1*1024*1024, // Max file size in bytes (10 MB)
        files: 10, //一次最多处理10张图片
    },
  //文件过滤配置
    fileFilter: function (req, file, cb) {
        var mimetypes = (['text/*', 'image/*', 'video/*', 'audio/*', 'application/zip']).join(',');
        var testItems = file.mimetype.split('/');
        if ((new RegExp('\\b' + testItems[0] + '/\\*', 'i')).test(mimetypes) || (new RegExp('\\*/' + testItems[1] + '\\b', 'i')).test(mimetypes) || (new RegExp('\\b' + testItems[0] + '/' + testItems[1] + '\\b', 'i')).test(mimetypes)) {
            cb(null, true);
        } else {
            return cb(new Error('Only image, plain text, audio, video and zip format files are allowed!'), false);
        }
    },
  //文件上传重命名
      filename: function (req, file, cb) {
        let extname = path.extname(file.originalname); // 取后缀名
        cb(null, file.fieldname + '-' + Date.now() + extname) //文件名加上时间戳
      }
})

上传文件

// upload.controller.js
import { dist } from "../../../app-config";
import multer  from "multer";

//后面的参数也可以参照文档提供的API进行适当调整
let upload = multer({storage: dist}).any()

//具体业务逻辑自己根据需求调整
let uploadFile = (req,res) => {
    upload(req, res, function (uploadError) {
        if (uploadError) {
            console.log(uploadError);
            res.send({
                'code': 500,
                'msg':'上传失败'
            })
            //错误处理
        } else {
              let data = req.files
            res.send({
                'code': 200,
                'data': data,
                'msg': '获取成功'
            })
        }
    });
}


module.exports = {
    uploadFile
}

最后将方法挂载到路由上即可使用

微信扫一扫体验微信小程序
Last modification:May 7th, 2022 at 05:34 pm
If you think my article is useful to you, please feel free to appreciate