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

node.js KoaJS

EvaEva斯丁

2020-04-07

当我发布多部分表格时,

<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 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);
  };
};

然后,我更改了代码

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);

没有错误,但我无法获取请求的数据:

debug(this.request.files.file);

结果不确定。

我正在使用KoaJ。

第4150篇《KoaJS如何从多部分表单数据中获取文件?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
古一 2020.04.07

好的。首先,您要发布的代码是来自的源代码,co-body因此,multipart/form-data如果不是为了实现此目的而添加数据包则不会神奇地强制该程序包处理多部分数据。

除了使用co-body之外,您还可以使用为处理而设计的co-busboymultipart/form-data

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android