【问题标题】:Express.js - Multer File Filter Not WorkingExpress.js - Multer 文件过滤器不起作用
【发布时间】:2022-01-06 02:15:21
【问题描述】:

我想在将文件上传到服务器时对其进行过滤,但 Multer fileFilter 方法不起作用。

后端

destinationfilename 方法也可以正常工作,但 fileFilter 不能正常工作。

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/images/");
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + path.extname(file.originalname));
  },
  fileFilter: function (req, file, callback) {
    console.log("Hello Word"); // This doesn't work either

    var ext = path.extname(file.originalname);
    if (!['.jpg', '.jpeg'].includes(ext)) {
      return callback(new Error('Only images are allowed'));
    }

    callback(null, true);
  },
});

app.use(
  multer({ storage: storage }).fields([
    { name: "logo", maxCount: 1 },
    { name: "favicon", maxCount: 1 },
  ])
);

前端

<form action="" method="post" enctype="multipart/form-data">
    <table>
        <tbody>
            <tr>
                <td>Logo</td>
                <td>
                    <input type="file" name="logo" accept="image/jpeg, image/jpg"/>
                </td>
            </tr>
            <tr>
                <td>Favicon</td>
                <td>
                    <input type="file" name="favicon" accept="image/x-icon" />
                </td>
            </tr>
        </tbody>
    </table>
</form>

【问题讨论】:

  • 请提供您的所有代码或存储库的链接;-) 控制台显示什么错误?
  • 这些答案解决了你的问题吗?
  • @MarioG8 是的,我解决了,非常感谢。
  • 所以您可以将我的回答标记为解决您的问题 ;-) 最好的问候!

标签: javascript node.js express multer


【解决方案1】:

您的filterMethod 工作正常。这可以通过更改input accept="image/*" 中的值来检查。然后当我们尝试加载icojpg 以外的文件时,我们将得到一个错误:Only images are allowed。 您的代码需要一些调整,另外我使用了 ejs module,这是我的解决方案建议:


文件夹和文件项目结构:

app.js - 使用您的 fileFilter 代码。

const path = require("path");
const express = require("express");
const multer = require("multer");
const app = express();

app.use(express.static(path.join(__dirname, "public")));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views"));

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./images");
  },
  filename: function (req, file, cb) {
    console.log(req.file);

    cb(null, new Date().toUTCString() + " - " + file.originalname);
  },
});

const upload = multer({
  storage: storage,
  fileFilter: function (req, file, callback) {
    console.log("Hello, World! Works fine;-)");

    var ext = path.extname(file.originalname);
    if (![".jpg", ".ico"].includes(ext)) {
      return callback(new Error("Only images are allowed"));
    }

    callback(null, true);
  },
});

app.post(
  "/post",
  upload.fields([
    { name: "logo", maxCount: 1 },
    { name: "favicon", maxCount: 1 },
  ]),
  (req, res, next) => {
    const files = req.files;
    if (!files) {
      const error = new Error("Please upload a file");
      error.httpStatusCode = 400;
      return next(error);
    }
    res.send(files);
    console.log("Success", req.files);
  }
);

app.get("/post", (req, res) => {
  res.render("post");
});

app.listen(3000, () => {
  console.log(`Example app listening at http://localhost:3000/post`);
})

post.ejs - 使用您的前端 form 代码和我的额外input submit

<form action="" method="post" enctype="multipart/form-data">
  <table>
    <tbody>
      <tr>
        <td>Logo</td>
        <td>
          <input type="file" name="logo" accept="image/jpeg, image/jpg" />
        </td>
      </tr>
      <tr>
        <td>Favicon</td>
        <td>
          <input type="file" name="favicon" accept="image/x-icon" />
        </td>
      </tr>
    </tbody>
  </table>
  <input class="submit" type="submit" value="Upload File" />
</form>

http://localhost:3000/post在浏览器中路由输出:


输出submit - Upload File 之后。 fields name logofavicon 中指定的文件。


输出server sideimages 文件夹中:

测试:node v16.13.0 "ejs": "^3.1.6","express": "^4.17.2","multer": "^1.4.4"

【讨论】:

  • 我删除了一些字段以使代码不那么可见。当我将upload.fields 添加到路线时,这很有效。非常感谢您的关注。
  • 不客气!最好的问候;-)
猜你喜欢
  • 2018-07-22
  • 1970-01-01
  • 2015-11-18
  • 2015-02-05
  • 1970-01-01
  • 2016-04-11
  • 2015-05-26
  • 2011-11-25
  • 1970-01-01
相关资源
最近更新 更多