多部分格式的数据文件上传时间错误主体应该是对象,而且我也在使用ajv插件,我仍然在使用同样的问题。下面是我的参考代码。
app.js
const fastify = require('fastify')({
logger: true
});
const Ajv = require('ajv');
const ajv = new Ajv({
useDefaults: true,
coerceTypes: true,
$data: true,
extendRefs: true
});
ajv.addKeyword("isFileType", {
compile: (schema, parent, it) => {
parent.type = "file";
delete parent.isFileType;
return () => true;
},
});
fastify.setSchemaCompiler((schema) => ajv.compile(schema));
routes.js
schema: {
tags: [{
name: 'Category'
}],
description: 'Post category data',
consumes: ['multipart/form-data'],
body: {
type: 'object',
isFileType: true,
properties: {
name: {
type: 'string'
},
thumb_url: {
isFileType: true,
type: 'object'
},
img_url: {
isFileType: true,
type: 'object'
},
status: {
type: 'number',
enum: [0, 1],
default: 1
}
},
required: ['name', 'thumb_url', 'img_url']
},
response: {
201: {
type: 'object',
properties: categoryProperties
}
}
}
响应
{
"statusCode": 400,
"error": "Bad Request",
"message": "body should be object"
}
我怀疑错误出在我发送数据的方式上,但我很难弄清楚这一点。我读到过这个错误,它似乎是在将一个对象传递给formData时生成的,但我发送的是一个字符串,所以我不明白为什么会发生这种情况。提前感谢!
发布于 2020-02-14 15:43:04
我认为你管理multipart的配置是错误的,模式应该按照这个工作示例进行修复:
const fastify = require('fastify')({ logger: true })
fastify.register(require('fastify-multipart'), {
addToBody: true
})
const Ajv = require('ajv')
const ajv = new Ajv({
useDefaults: true,
coerceTypes: true,
$data: true,
extendRefs: true
})
ajv.addKeyword('isFileType', {
compile: (schema, parent, it) => {
parent.type = 'file'
delete parent.isFileType
return () => true
}
})
fastify.setSchemaCompiler((schema) => ajv.compile(schema))
fastify.post('/', {
schema: {
tags: [{
name: 'Category'
}],
description: 'Post category data',
consumes: ['multipart/form-data'],
body: {
type: 'object',
properties: {
name: { type: 'string' },
thumb_url: { isFileType: true },
img_url: { isFileType: true },
status: {
type: 'number',
enum: [0, 1],
default: 1
}
},
required: ['name', 'thumb_url', 'img_url']
}
}
}, async (req, reply) => {
let filepath = path.join(__dirname, `${req.body.thumb_url[0].filename}-${Date.now()}`)
await fs.writeFile(filepath, (req.body.thumb_url[0].data))
filepath = path.join(__dirname, `${req.body.img_url[0].filename}-${Date.now()}`)
await fs.writeFile(filepath, (req.body.img_url[0].data))
return req.body
})
fastify.listen(3000)
使用以下请求调用它:
curl -X POST \
http://127.0.0.1:3000/ \
-H 'content-type: multipart/form-data' \
-F 'thumb_url=@/home/wks/example-file' \
-F 'img_url=@/home/wks/example-file' \
-F 'name=fooo'
您将获得:
{
"thumb_url":[
{
"data":{
"type":"Buffer",
"data":[
97,
115,
100,
10
]
},
"filename":"example-file",
"encoding":"7bit",
"mimetype":"application/octet-stream",
"limit":false
}
],
"img_url":[
{
"data":{
"type":"Buffer",
"data":[
97,
115,
100,
10
]
},
"filename":"example-file",
"encoding":"7bit",
"mimetype":"application/octet-stream",
"limit":false
}
],
"name":"foo",
"status":1
}
https://stackoverflow.com/questions/60221062
复制相似问题