如何使用OpenAPI 3和Nodejs中的Multer获得所有多形/数据形式的领域

发布于 2025-01-20 15:27:25 字数 2534 浏览 1 评论 0原文

我想要完成的任务是上传包含多个其他字段的其他文本数据的文件(所附屏幕截图中的示例)。

输入图片此处描述

我正在使用 Express 和 Multer,我的问题是我的控制器无法获取图像文件和 2 个文本字段。我只接收图像(req.files 不为空,但 req.body 为空)。

这是我的代码示例:

const express = require('express');
const app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.text());

const path = require('path');
const apiSpec = path.join(__dirname, './api.yaml');
const OpenApiValidator = require('express-openapi-validator');
app.use(OpenApiValidator.middleware({
  apiSpec: apiSpec,
  additionalProperties: false,
  validateRequests: true,
  validateResponses: false
}));

const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

app.post('/upload', upload.single('fileUpload'), (req, res) => {
    try {
        console.log(req.files);
        console.log(req.body);

        // UPLOAD LOGIC . . .

        res.status(201).send();
    } catch (err) {
        next(err)
    }
});

我的输出如下:

(1) [{...}]     //THIS IS req.files
{}              //THIS IS req.body

req.files 仅包含一项,即图像上传,但没有 fileIdauthor 的踪迹

知道我做错了什么吗?

注意:另请注意,如果我使用 upload.fields([{ name: fieldName, maxCount: 1}, ...])upload.any() 我获取 req.files[]



更新

感谢taipei的回答确实帮助我重定向了我的搜索。我没有提到我也在使用 OpenApiValidator (express-openapi-validator),并且通过禁用它,一切都工作正常,所以我相信这些一定是我的 api 中出现的问题。 yml 配置

  /upload:
    post:
      summary: Upload file with text data
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                fileId:
                  type: string
                fileUpload:
                  type: string
                  format: binary
                author:
                  type: string
      responses:
        '201':
          description: Uploaded file with text data
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: 
                    type: string

感谢大家的帮助,如果我遗漏了任何细节,请告诉我。

What I want to accomplish it to upload a file with other text data of multiple other fields (example in the attached screenshot).

enter image description here

I am using Express and Multer, my problem is that my controller couldn't get the image file and the 2 text fields. I am only receiving the image (req.files not empty but req.body is empty).

here is my code sample:

const express = require('express');
const app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.text());

const path = require('path');
const apiSpec = path.join(__dirname, './api.yaml');
const OpenApiValidator = require('express-openapi-validator');
app.use(OpenApiValidator.middleware({
  apiSpec: apiSpec,
  additionalProperties: false,
  validateRequests: true,
  validateResponses: false
}));

const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

app.post('/upload', upload.single('fileUpload'), (req, res) => {
    try {
        console.log(req.files);
        console.log(req.body);

        // UPLOAD LOGIC . . .

        res.status(201).send();
    } catch (err) {
        next(err)
    }
});

My output is as follow:

(1) [{...}]     //THIS IS req.files
{}              //THIS IS req.body

the req.files hold only one item which is the image upload, but no trace of fileId and author.

Any idea of what am I doing wrong?

NOTE: Please also note that if I use upload.fields([{ name: fieldName, maxCount: 1}, ...]) or upload.any() I get [] for req.files.



UPDATE

Thanks to taipei's answer that did help me redirect my searches. I didn't mention that I am also using OpenApiValidator (express-openapi-validator) and by disabling it, everything did work fine, so I believe these must be something off in my api.yml configuration

  /upload:
    post:
      summary: Upload file with text data
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                fileId:
                  type: string
                fileUpload:
                  type: string
                  format: binary
                author:
                  type: string
      responses:
        '201':
          description: Uploaded file with text data
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: 
                    type: string

Thank you all for your assistance, if I missed any details please let me know.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里寻她 2025-01-27 15:27:25

您需要指定文件的表单数据字段名称。
对于您的示例,您需要使用 fileUpload 作为 upload.single() 中的参数值

,而且我认为您不能使用根 ( / ) 作为路径,您需要为请求使用特定路径。

...
app.post('/upload', upload.single('fileUpload'), (req, res) => {
...

在您的逻辑中,由于您只使用单个文件,因此您需要使用 req.file 而不是 req.files

您可以在此处查看完整的代码

const express = require('express')
const app = express()
const port = 3000

app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.text());

const multer  = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

app.post('/upload', upload.single('fileUpload'), (req, res) => {
    try {
        console.log(req.file);
        console.log(req.body);

        // UPLOAD LOGIC . . .

        res.status(201).send();
    } catch (err) {
        next(err)
    }
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

参考:

https://www.npmjs.com/package/multer

You need to specify the form-data field name for the file.
For your example, you need to use fileUpload as the param value in upload.single()

And I think you can't use the root ( / ) as the path, you need to use a specific path for the request.

...
app.post('/upload', upload.single('fileUpload'), (req, res) => {
...

in your logic, since you only use a single file, you need to use req.file instead of req.files

you can see the full code here

const express = require('express')
const app = express()
const port = 3000

app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.text());

const multer  = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

app.post('/upload', upload.single('fileUpload'), (req, res) => {
    try {
        console.log(req.file);
        console.log(req.body);

        // UPLOAD LOGIC . . .

        res.status(201).send();
    } catch (err) {
        next(err)
    }
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

references:

https://www.npmjs.com/package/multer

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文