koa文件上传中间件——koa-multer

koa-multer用法基本和multer一致,npm里koa-multer的用法介绍比较简单,可以参考multer的用法

 

使用

const Koa = require('koa');
const Router = require('koa-router');
const multer = require('koa-multer');
const path = require('path');

const server = new Koa();

let storage = multer.diskStorage({
    destination: path.resolve('upload'),
    filename: (ctx, file, cb)=>{
        cb(null, file.originalname);
    }
});
let fileFilter = (ctx, file ,cb)=>{
//过滤上传的后缀为txt的文件
    if (file.originalname.split('.').splice(-1) == 'txt'){
        cb(null, false); 
    }else {
        cb(null, true); 
    }
}
let upload = multer({ storage: storage, fileFilter: fileFilter });

let router = new Router();
router.post('/upload', upload.single('file'), async ctx => {
    if (ctx.req.file){
        ctx.body = 'upload success';
    } else {
        ctx.body = 'upload error';
    }
});
server.use(router.routes());

server.listen(8080, ()=>{
    console.log('usage: curl http://localhost:8080/upload -F "file=@1.jpg"');
});

测试:

curl http://localhost:8080/upload -F "file=@1.jpg"
>> upload success
curl http://localhost:8080/upload -F "file=@1.txt"
>> upload error

 

说明
文件信息
KeyDescription Note
fieldnameField name specified in the form
originalnameName of the file on the user’s computer
encodingEncoding type of the file
mimetypeMime type of the file
sizeSize of the file in bytes
destinationThe folder to which the file has been saved DiskStorage
filenameThe name of the file within the destination DiskStorage
pathThe full path to the uploaded file DiskStorage
bufferA Buffer of the entire file MemoryStorage
multer(opts)

opts参数

KeyDescription
dest or storageWhere to store the files
fileFilterFunction to control which files are accepted
limitsLimits of the uploaded data
preservePathKeep the full path of files instead of just the base name
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值