【Deno】m_oak_upload文件上传中间件

背景

最近在写一个API项目涉及到文件上传,之前NodeJS有multer库可以快速实现功能。很遗憾目前没有deno版的,体验了几个现有deno版的upload库都不理想基本上都在报错。为了方便使用小溪基于deno1.34版本封装了一个文件上传中间件。文末附项目地址

功能简介

基于oak的文件上传中间件

配置

默认配置

maxFileSize: 5M
randomName: true

import { upload } from 'https://deno.land/x/m_oak_upload';

router.post('/upload', upload("uploads") , UploadController.upload)

限制文件大小

import { upload } from 'https://deno.land/x/m_oak_upload';

router.post('/upload', upload("uploads", { maxFileSize: 2*1024*1024, randomName: true }) , UploadController.upload)

随机文件名称

import { upload } from 'https://deno.land/x/m_oak_upload';

router.post('/upload', upload("uploads", { randomName: true }) , UploadController.upload)

文件名称过滤

import { upload } from 'https://deno.land/x/m_oak_upload';

router.post('/upload', upload("uploads", { files: ['file', 'file2'] }) , UploadController.upload)

文件数量限制

import { upload } from 'https://deno.land/x/m_oak_upload';

router.post('/upload', upload("uploads", { maxFile: 2  }) , UploadController.upload)

文件后缀过滤

import { upload } from 'https://deno.land/x/m_oak_upload';

router.post('/upload', upload("uploads", { exts: ['ts', 'png', 'jpg'] }) , UploadController.upload)

获取上传结果

中间件会将文件上传结果挂载到context上下文的uploads

const upload = (ctx: any) => {
  const { files, errors } = ctx.uploads
  // 处理错误
  if (errors) {
    ctx.response.body = response(400, errors)
    return
  }
  const retArr:Omit<IFile, 'originalName'|'tmpUrl'|'path'>[] = []
  // 没有错误
  if (files) {
    const uploadFilesList = files as IFile[]
    for (const uploadFile of uploadFilesList) {
      retArr.push({
        fileName: uploadFile.fileName,
        name: uploadFile.name,
        ext: uploadFile.ext,
        size: uploadFile.size,
        url: uploadFile.url
      })
    }
  }
  ctx.response.body = response(200, retArr)
}

deno.land

https://deno.land/x/m_oak_upload

oak upload

https://github.com/m-deno/m-oak-upload

API项目

https://github.com/MisterZhouZhou/mz-deno-api/tree/main

你可能感兴趣的:(Deno学习笔记,deno,oak,upload)