KoaJS如何从多部分表单数据获取文件?

当我发布多部分表单时,

<form name="acount_manage" action="/update" enctype="multipart/form-data" method="post"> <input type="file" name="file"> </form> 

它抛出:

 Error: Unsupported content-type: multipart/form-data at Object.<anonymous> (e:\...\node_modules\co-body\lib\any.js:51:15) 

any.js:

 /** * Module dependencies. */ var json = require('./json'); var form = require('./form'); var text = require('./text'); var JSON_CONTENT_TYPES = [ 'application/json', 'application/json-patch+json', 'application/vnd.api+json', 'application/csp-report', 'application/ld+json' ]; /** * Return aa thunk which parses form and json requests * depending on the Content-Type. * * Pass a node request or an object with `.req`, * such as a koa Context. * * @param {Request} req * @param {Options} [opts] * @return {Function} * @api public */ module.exports = function(req, opts){ req = req.req || req; // parse Content-Type var type = req.headers['content-type'] || ''; type = type.split(';')[0]; // json if (~JSON_CONTENT_TYPES.indexOf(type)) return json(req, opts); // form if ('application/x-www-form-urlencoded' == type) return form(req, opts); // text if ('text/plain' == type) return text(req, opts); // invalid return function(done){ var message = type ? 'Unsupported content-type: ' + type : 'Missing content-type'; var err = new Error(message); err.status = 415; done(err); }; }; 

然后,我改变了代码

 if ('application/x-www-form-urlencoded' == type) return form(req, opts); 

 if ('application/x-www-form-urlencoded' == type || 'multipart/form-data'==type) return form(req, opts); 

没有错误,但我无法得到request'data:

 debug(this.request.files.file); 

结果是未定义的。

我正在使用KoaJs。

对于koa 2 ,尝试使用async-busboy来parsing请求体,因为co-busboy与基于promise的asynchronous不兼容。

来自文档的示例:

 import asyncBusboy from 'async-busboy'; // Koa 2 middleware async function(ctx, next) { const {files, fields} = await asyncBusboy(ctx.req); // Make some validation on the fields before upload to S3 if ( checkFiles(fields) ) { files.map(uploadFilesToS3) } else { return 'error'; } } 

好的。 首先你要发布的代码是co-body的源代码,所以在multipart/form-datajoin这些代码并不会强制这个包处理多部分数据,如果不是这样做的话。

而不是使用合作机构,你可以使用co-busboy来处理multipart/form-data

尝试koa身体图书馆。

例:

把这个中间件放在路由中间件之前:

 app.use(require('koa-body')({ formidable:{ uploadDir: __dirname + '/public/uploads', // directory where files will be uploaded keepExtensions: true // keep file extension on upload }, multipart: true, urlencoded: true, })); 

然后在路由中间件中使用

 async function(ctx, next) { ctx.request.body.files.file // file is the input name } 

这个代码适用于KoaJs 2,但是这个库也适用于KoaJs 1。