如何使用Koa.JS 2上传文件?我尝试使用koa.js,但没有在ctx
对象中获取文件。
答案 0 :(得分:1)
这些是我们最好的选择
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;
});
尝试在上传之前进行一些验证(如果文件存在,请更改名称)-部分示例代码:
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')
})
})