如何使用Koa.JS 2上传文件?我尝试使用koa.js,但没有获得ctx对象中的文件。
发布于 2018-10-02 04:35:43
这些是你最好的选择
@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')
})
})https://stackoverflow.com/questions/52596764
复制相似问题