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 "[email protected]"');
});

测试:

curl http://localhost:8080/upload -F "[email protected]"
>> upload success
curl http://localhost:8080/upload -F "[email protected]"
>> upload error

 

说明

文件信息
Key Description Note
fieldname Field name specified in the form
originalname Name of the file on the user’s computer
encoding Encoding type of the file
mimetype Mime type of the file
size Size of the file in bytes
destination The folder to which the file has been saved DiskStorage
filename The name of the file within the destination DiskStorage
path The full path to the uploaded file DiskStorage
buffer A Buffer of the entire file MemoryStorage
multer(opts)

opts参数

Key Description
dest or storage Where to store the files
fileFilter Function to control which files are accepted
limits Limits of the uploaded data
preservePath Keep the full path of files instead of just the base name

你可能感兴趣的:(Koa)