0

我正在尝试将图像上传到我的 node.js 服务器,当我什么都不上传并且只发送请求以发布没有图像时,它工作正常但是每当我尝试发布图像时 node.js 在控制台中显示错误

这是发布“http://localhost:3001/databaseGym/logo”的链接这是我处理对该链接的发布操作的代码

 Router.post('/logo', upload.single('file'), (req, res) => {
    console.log("working");
    //res.json({ file: req.file });
    res.send("done");
  });

这是我在 upload.single() 中上传的代码

// Create storage engine
const storage = new GridFsStorage({
  url: url,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'logo'
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({ storage });

这是邮递员应用程序的屏幕截图,我通过它发送图像 邮递员应用程序图像

这是错误

MulterError: Unexpected field
    at wrappedFileFilter (D:\web dev\gym website\server_gym\node_modules\multer\index.js:40:19)
    at Busboy.<anonymous> (D:\web dev\gym website\server_gym\node_modules\multer\lib\make-middleware.js:114:7)
    at Busboy.emit (node:events:394:28)
    at Busboy.emit (D:\web dev\gym website\server_gym\node_modules\busboy\lib\main.js:38:33)
    at PartStream.<anonymous> (D:\web dev\gym website\server_gym\node_modules\busboy\lib\types\multipart.js:213:13)
    at PartStream.emit (node:events:394:28)
    at HeaderParser.<anonymous> (D:\web dev\gym website\server_gym\node_modules\dicer\lib\Dicer.js:51:16)
    at HeaderParser.emit (node:events:394:28)
    at HeaderParser._finish (D:\web dev\gym website\server_gym\node_modules\dicer\lib\HeaderParser.js:68:8)
    at SBMH.<anonymous> (D:\web dev\gym website\server_gym\node_modules\dicer\lib\HeaderParser.js:40:12)
4

1 回答 1

2

当您在 POST 端点中指定属性名称时,您应该将 Postman 中的参数从image更改为:file

// you specify the `file` as the fieldname
Router.post('/logo', upload.single('file'), (req, res) => {
    console.log("working");
    //res.json({ file: req.file });
    res.send("done");
  });

从文档:

.single(fieldname)

接受一个名为fieldname. 单个文件将存储在req.file.

于 2021-09-21T17:59:08.450 回答