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

lic*_*125 6 forms node.js koa

当我发布多部分表格时,

<form name="acount_manage"  action="/update" enctype="multipart/form-data" method="post">
    <input type="file" name="file">
</form>
Run Code Online (Sandbox Code Playgroud)

它抛出:

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

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 a a 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);
  };
};
Run Code Online (Sandbox Code Playgroud)

然后,我改变了代码

if ('application/x-www-form-urlencoded' == type) return form(req, opts);
Run Code Online (Sandbox Code Playgroud)

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

没有错误,但我无法得到请求数据:

debug(this.request.files.file);
Run Code Online (Sandbox Code Playgroud)

结果未定义.

我正在使用KoaJs.

Pea*_*yle 0

好的。首先,您发布的代码是源代码,因此co-body添加multipart/form-data不会神奇地强制此包处理多部分数据(如果它不是为此而构建的)。

您可以使用co-busboy,而不是使用co-body,它是为处理multipart/form-data.