如何使用 Multer 提交带有可选文件提交的表单?

Tan*_*lam 7 javascript forms node.js express multer

我正在使用 multer 在我的快递应用程序中提交表单。问题是表单有可选的图像提交选项。这意味着用户可以根据需要添加照片,但他/她也可以提交没有图像的表单。图片提交没有问题。但是当没有图像时,multer 不会提交表单,甚至没有其他字段。

const express = require('express');
const router = express.Router();
const Company = require('../controller/CompanyController');
const multer  = require('multer');
const path = require('path');

let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images/logos');
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

let upload = multer({ storage: storage }).any();

router.route('/companies').post(upload, Company.Create);

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

Jaz*_*tha 9

一种解决方法是检查req.file提交通过后的值。如果您未在表单中提供文件,req.file则其值应为undefined. 但是,如果您提交文件,它应该是object. 因此,您可以if像这样编写一个简单的语句:

function Create() {
  if (req.file !== undefined) {
  // process image here
  }
  // process all other fields
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!