如何使用Koa.JS 2上传文件?

时间:2018-10-01 18:22:34

标签: node.js file-upload upload koa koa2

如何使用Koa.JS 2上传文件?我尝试使用koa.js,但没有在ctx对象中获取文件。

1 个答案:

答案 0 :(得分:1)

这些是我们最好的选择

async-busboy

koa-multer

koa-multer示例:

import Router from 'koa-router';
import multer from 'koa-multer';

const router = new Router();

const upload = multer({
 storage: multer.memoryStorage()
});

router.post('/upload', upload.single('document'), async ctx => {
const { file } = ctx.req;

// Do stuff with the file here

ctx.status = 200;
});

source

尝试在上传之前进行一些验证(如果文件存在,请更改名称)-部分示例代码:

let storage = multer.diskStorage({
 destination: function(req, file, callback) {
    callback(null, './public/uploads')
 },
 filename: function(req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now() + 
 path.extname(file.originalname))
    //callback(null, file.originalname)
 }
})

app.post('/api/file', function(req, res) {
var upload = multer({
    storage: storage}).single('userFile');
upload(req, res, function(err) {
    console.log("File uploaded");
    res.end('File is uploaded')
})
})

example source