Skip to content

Commit

Permalink
feat: 配置生成multer文件上传器
Browse files Browse the repository at this point in the history
  • Loading branch information
fanzhiwen committed Sep 11, 2023
1 parent b18fcbd commit bd8654c
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/loaders/middleware/multer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import express from 'express'
import { multerUploader } from './uploader'

/**
* 上传单个文件
* req.file is the <filedName> file
* req.body will hold the text fields, if there were any
*
* @param filedName 上传文件的字段名
*/
const uploadSingleFile = (filedName: string): express.RequestHandler => {
return multerUploader.single(filedName)
}

/**
* 上传多个文件
* req.files is array of <filedName> files
* req.body will contain the text fields, if there were any
*
* @param filedName 上传文件的字段名
* @param maxCount 最大上传数量
*/
const uploadMultiFiles = (filedName: string, maxCount?: number): express.RequestHandler => {
return multerUploader.array(filedName, maxCount)
}

/**
* 类型定义:自定义上传多个文件的参数(单个)
*/
interface uploadCustomFilesParam {
/** 上传文件的字段名 */
name: string
/** 某字段名的文件的最大上传数量 */
maxCount: number
}

/**
* 自定义上传多个文件
* req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
*
* e.g.
* req.files['avatar'][0] -> File
* req.files['gallery'] -> Array
*
* req.body will contain the text fields, if there were any
*
* @param params 自定义上传多个文件的参数
*/
const uploadCustomFiles = (params: uploadCustomFilesParam[]): express.RequestHandler => {
return multerUploader.fields(params)
}

export { uploadSingleFile, uploadMultiFiles, uploadCustomFiles }
21 changes: 21 additions & 0 deletions src/loaders/middleware/multer/uploader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// 配置multer,生成文件上传器
// 使用到的中间件 - multer:https://github.com/expressjs/multer

import path from 'path'
import multer from 'multer'
import config from '@/_config/config'

/** 使用multer上传文件的路径 */
const DESTPATH = path.join(config.uploadDir, 'temp')

/**
* multer配置
* - 目标路径
*/
const multerOpts: multer.Options = {
dest: DESTPATH
}

const multerUploader = multer(multerOpts)

export { multerUploader }

0 comments on commit bd8654c

Please sign in to comment.