当我发布多部分表格时,
<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);
};
};
&#13;
然后,我改变了代码
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);
没有错误,但我无法获得请求&#39;数据:
debug(this.request.files.file);
结果未定义。
我正在使用KoaJs。
答案 0 :(得分:1)
对于 koa 2 ,请尝试async-busboy解析请求正文 基于承诺的异步,co-busboy不能很好地发挥作用。
文档示例:
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';
}
}
答案 1 :(得分:1)
试试koa-body库。
示例:
在路由中间件之前放置此中间件:
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。
答案 2 :(得分:0)