最近在写一个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)
}
https://deno.land/x/m_oak_upload
https://github.com/m-deno/m-oak-upload
https://github.com/MisterZhouZhou/mz-deno-api/tree/main